C# notes

some of these notes may have been created from other online sources.

they are just my home schooling notes.

 

when doing math operations the result is the result of the types used in the math operation.
so if you have 2 floats, the answer is float.
if you have to ints then the answer is int.
when doing math the “compiler” rounds towards 0.
so 2/5 = 2. not 2.5 because it is not of type float and it rounds to zero.

if you use 5/2.0 to compiler changes the int to a double and you get 2.5

int addValues(int leftHandSide, int rightHandSide)
{
// …
// method body statements go here
// …
return 0;
}

when calling a function which takes an int don’t forget you do not put the number in double quotes (“”)
if you do it is treated as a string.

so to call addValues: addValues(2,3);

void returnNothing()
{
// code here
return;   //returns nothing
}

using a function to initialize a value for a variable:
int leftHandSide = System.Int32.Parse(lhsOperand.Text);
int rightHandSide = System.Int32.Parse(rhsOperand.Text);

However, keep in mind that although you can overload the
parameters of a method, you can’t overload the return type of a method
In other words, you can’t declare two methods with the same name that differ only in their return type.

The Console.Write method is similar to the Console.WriteLine statement that you have used in earlier exercises,
except that it does not output a newline character after the message.

logical AND(&&)
logical OR (||)

anything besides 0 is true

if ( booleanExpression )
statement-1;
else
statement-2;

if (a)
{
//
}
else if(b)
{
//
}

bool inWord;

if (inWord == true) // ok, but not commonly used

if (inWord) // more common and considered better style

———————————————————————
SWITCH STATEMENTS:
note for switch statements: break is required for every element in the switch statement. if you want it to fall through to another element use a goto statement

private void copyOne(char current)
{
switch (current)
{
case ‘<‘ :
target.Text += “&lt;”;
break;
case ‘>’ :
target.Text += “&gt;”;
break;
case ‘&’ :
target.Text += “&amp;”;
break;
case ‘”‘ :
target.Text += “&#34;”;
break;
case ”’ :
target.Text += “&#39;”;
break;

default:
target.Text += current;
break;
}
}

————————————————————————
you can use break at any time in the looping statements to break out of the loop.

WHILE STATEMENTS:

int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
————————————————————————
FOR STATEMENTS:

for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}

you can initialize more than one variable:
for (int i = 0, j = 10; i <= j; i++, j–)
{

}
————————————————————————
THE DO STATEMENT:

int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (
i
<
10);

————————————————————————
EXCEPTION HANDLING:
you put the code to be error handled in the try block.
if an exception is thrown the catch block will execute.
after a catch is executed the flow of execution goes to the first statement after the handler
the finally block is run after the exception is handled (or not handled)

try {
//code here
}

catch (Exception myException)
{
//code here
}

finally
{
if (reader != null)
{
reader.Dispose();
}
}

checked and unchecked
All integer arithmetic in a checked statement always throws an OverflowException if an integer calculation in the block overflows
All integerarithmetic in an unchecked block is not checked and never throws an OverflowException.
The checked and unchecked keywords apply only to integer arithmetic using data types such as int and long.
Floating-point arithmetic never throws OverflowException—not even when you divide by 0.0.

int number = int.MaxValue;
checked
{
int willThrow = number++;
Console.WriteLine(“this won’t be reached”);
}

int number = int.MaxValue;
unchecked
{
int wontThrow = number++;
Console.WriteLine(“this will be reached”);
}

int wontThrow = unchecked(int.MaxValue + 1);
int willThrow = checked(int.MaxValue + 1);

private void calculateClick(object sender, RoutedEventArgs e)
{
try
{

}
catch (FormatException fEx)
{
result.Text = fEx.Message;
}
catch (OverflowException oEx)
{
result.Text = oEx.Message;
}
}

thowing an error when something is out of range:

public static string monthName(int month)
{
switch (month)
{
case 1 :
return “January”;
case 2 :
return “February”;

case 12 :
return “December”;
default :
throw new ArgumentOutOfRangeException(“Bad month”);
}
}

——————————————————
CLASSES:
to share a variable between class objects (instead of them each having their own set of values) mark the data member static
you can also have static classes but they require all data members to be static, and you can not create an object of the static class using new.

public static class myclass {            //public static class
public static int variable = 1;   //static variable

public myclass()
{
//code for constructor here
}

~myclass () //destructor
{
//codehere
}

}

accessing members of a class using the dot operator:
mySquare.Draw();  //calls the Draw function from mySquare object

you can also have anonymous classes.
when you create the anonymous class you omit the keyword class.
myAnonymousObject = new { Name = “John”, Age = 47 };  //example anonymous class
Console.Writeline(“Name={0}”, myAnonymousObject.Name);

you can also use the var keyword to create variables of the same type used to initialize them.
var myAnonymousObject = new { Name = “John”, Age = 47 };
Console.WriteLine(“Name: {0} Age: {1}”, myAnonymousObject.Name, myAnonymousObject.Age};

public class Math
{

public const double PI = 3.14159265358979323846;  //a const value which all instances of Math will have
}

class Circle
{
private int radius;
public Circle() // default constructor
{
radius = 0;
}
public Circle(int initialRadius) // overloaded constructor
{
radius = initialRadius;
}
public double Area()
{
return Math.PI * radius * radius;
}
}

Circle c; // Create a Circle variable
c = new Circle(); // Initialize it
OR
c = new Circle(45); //Initialize it with a value for radius
double areaOfCircle = c.Area();  //use method from class to set variable

you can also chop up a class into mutiple partial definitions, they act as one class when compiled.

file1:
partial class Circle
{
private int radius;
public double Area()
{
return Math.PI * this.radius * this.radius;
}
}

file2:
partial class Circle
{
public Circle() // default constructor
{
this.radius = 0;
}
public Circle(int initialRadius) // overloaded constructor
{
this.radius = initialRadius;
}
}

when you have a couple objects and you make one = the other they both point to the same space on the heap.

CLASS INHERITANCE:

The derived class inherits from the base class, and the methods in the base class become part of the derived class.
In addition to the methods that it inherits, a derived class automatically contains all the fields from the base class.

class DerivedClass : BaseClass  //baseclass is the class you inherit from, derivedclass is the new class
{

}

a class is allowed to derive from, at most, one base class; a class is not allowed
to derive from two or more classes. However, unless DerivedClass is declared as sealed, you can
create further derived classes that inherit from DerivedClass using the same syntax.

class DerivedSubClass : DerivedClass
{

}

It is good practice for a constructor in a derived class to call the constructor for its base class as part
of the initialization, which enables the base-class constructor to perform any additional initialization
that it requires. You can specify the base keyword to call a base-class constructor when you define a
constructor for an inheriting class, as shown in this example:
class Mammal // base class
{
public Mammal(string name) // constructor for base class
{

}

} class Horse :
Mammal // derived class
{
public Horse(string name)
: base(name) // calls Mammal(name)
{

}

}

you can assign a derived class to point to a base class, but you can only access the stuff that was in the base class
you can not assign a base class to point to a derived class.

Horse myHorse = new Horse(…);
Mammal myMammal = myHorse;    //derived class to point to a base class
myMammal.Breathe(); // OK – Breathe is part of the Mammal class

Mammal myMammal = newMammal(…);
Horse myHorse = myMammal; // error a base class points to a derived class

HAVING MUTIPLE FUNCTIONS THTA HAVE THE SAME NAME IN BASE AND DERIVED CLASSES:
class Mammal
{

public void Talk()
{

}
} class Horse :
Mammal
{

new public void Talk() //use keyword new to create function with the same name as one in the base class
{

}
}

A method that is intended to be overridden is called a virtual method.
You should be clear on the
difference between overriding a method and hiding a method. Overriding a method is a mechanism
for providing different implementations of the same method—the methods are all related because they
are intended to perform the same task, but in a class-specific manner. Hiding a method is a means of
replacing one method with another—the methods are usually unrelated and might perform totally
different tasks.

CREATING VIRTUAL METHODS:
A virtual method cannot be private;
The signatures of the virtual and override methods must be identical;
You can only override a virtual method.
If the derived class does not declare the method by using the override keyword, it does not
override the base class method; it hides the method.

namespace System
{
class Object
{
public virtual string ToString() //virtual method ment to be overrided
{

}

}

}

class Horse : Mammal
{

public override string ToString() //override virtual method
{

}
}

If a class A is derived from another class B, it can access the protected class members of class B.
In other words, inside the derived class A, a protected member of class B is effectively public.
If a class A is not derived from another class B, it cannot access any protected members of class
B. So, within class A, a protected member of class B is effectively private.
You can access a protected base class member not only in a derived class but also in classes derived from the derived
class.

Using an extension method, you can extend an existing type (a class or a structure) with additional
static methods.These static methods become immediately available to your code in any statements
that reference data of the type being extended.

static class Util //needs to be a static class
{
public static int Negate(this int i)  //the this keyword identifies it as an extension method
{
return -i;
}
}

int x = 591;
Console.WriteLine(“x.Negate {0}”, x.Negate()); //call the negate function

INTERFACES:
you use the keyword interface before the interface name
interfaces can not contain any data and can not be public, private, or protected
To implement an interface, you declare a class or structure that inherits from the interface and that
implements all the methods specified by the interface.
A class can have at most one base class, but it is allowed to implement an unlimited number of
interfaces. A class must implement all the methods declared by these interfaces.
An interface is not allowed to inherit from a structure or a class, although an interface can inherit
from another interface.

The method names and return types match exactly.
Any parameters (including ref and out keyword modifiers) match exactly.
All methods implementing an interface must be publicly accessible. However, if you are using an
explicit interface implementation, the method should not have an access qualifier.

interface ILandBound
{
int NumberOfLegs();
}

class Horse : ILandBound  //inherits the interface
{

public int NumberOfLegs()
{
return 4;

class can inherit from another class and implement an interface at the same time.
The base class is always named first, followed by a comma, followed by the interface.

In the same way that you can reference an object by using a variable defined as a class that is higher
up the hierarchy, you can reference an object by using a variable defined as an interface that its class
implements.

This works because all horses are land-bound mammals, although the converse is not true—you
cannot assign an ILandBound object to a Horse variable without casting it first to verify that it does
actually reference a Horse object and not some other class that also happens to implement the
ILandBound interface.

Horse myHorse = new Horse(…);
ILandBound iMyHorse = myHorse; // legal

You can verify that an object is an instance of a class that implements a specific interface by using the is operator

if (myHorse is ILandBound)
{
ILandBound iLandBoundAnimal = myHorse;
}

class Horse : ILandBound, IJourney
{

int ILandBound.NumberOfLegs()  //specifies which interface the method belongs to explicitly
{
return 4;
}
int IJourney.NumberOfLegs()  //specifies which interface the method belongs to explicitly

{
return 3;
}
}

ABSTRACT CLASSES:
An abstract class can contain abstract methods. An abstract method is similar in principle to a virtual
method , except that it does not contain a method body. A derived
class must override this method.
To declare that creating instances of a class is not allowed, you can declare that the class is abstract
by using the abstract keyword, such as in the following example:

abstract class GrazingMammal : Mammal, IGrazable
{

}

SEALED CLASSES:
With C#, you can use the sealed keyword to prevent
a class from being used as a base class if you decide that it should not be.
You can also use the sealed keyword to declare that an individual method in an unsealed class is
sealed. This means that a derived class cannot override this method.
You can seal only an override method, and you declare the method as sealed override.

For example:
sealed class Horse : GrazingMammal, ILandBound
{

}

GARBAGE COLLECTION:
you can make use of the “using” keyword to create an object and have it disposed of when you are done using it.
The variable you declare in a using statement must be of a type that implements the IDisposable
interface. The IDisposable interface lives in the System namespace and contains just one method, named Dispose

example use:

using (TextReader reader = new StreamReader(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}

USING GET AND SET:
get and set are ways of reading and writing to private fields in a class.
first a field is created (a variable)
mark it private
then a function like definition containing the get and set fucntions is declared
note that this function like definition does not have () in its definition.
notice to write to a private variable using the set method you access it like a variable:
e1.Name = “Claude Vige”;
you can choose to have only a get or set method, which makes it read or write only.
you do not need both get and set all the time
one thing to note is what when using this method of accessing values in fields THEY CAN NOT BE PASSED AS PARAMATERS TO OTHER FUNCTIONS.
A property can contain at most one get accessor and one set accessor.
The get and set accessors cannot take any parameters.

public class Employee
{
public static int NumberOfEmployees;
private static int counter;
private string name;

// A read-write instance property:
public string Name
{
get { return name; }
set { name = value; }
}

// A read-only static property:
public static int Counter
{
get { return counter; }
}

// A Constructor:
public Employee()
{
// Calculate the employee’s number:
counter = ++counter + NumberOfEmployees;
}
}

class TestEmployee
{
static void Main()
{
Employee.NumberOfEmployees = 107;
Employee e1 = new Employee();
e1.Name = “Claude Vige”;

System.Console.WriteLine(“Employee number: {0}”, Employee.Counter);
System.Console.WriteLine(“Employee name: {0}”, e1.Name);
}
}
/* Output:
Employee number: 108
Employee name: Claude Vige
*/

working with get and set with interfaces:

interface IScreenPosition
{
int X { get; set; }  //interface declaring get and set
int Y { get; set; }  //interface declaring get and set
}

note that since the interface created both get and set methods, you must define both in the struct

struct ScreenPosition : IScreenPosition  //a struct defined which inherits the interface with get and set
{

public int X
{
get { … }  //definition for get
set { … }  //definition for set
}
public int Y
{
get { … }  //definition for get
set { … }  //definition for set
}

}

GENERIC CLASSES:
Generics allow you to delay the specification of the data type of programming elements in a class or a method,
until it is actually used in the program.

generic classes are where the class specifies a placeholder for a data type which will be used by
the class when the object is instantiated. The functions and data members can also use this temporary type
and then later when used specify an actual type. msdn seems to use <T> as the temporary type but you can use any letter.

class Queue<T> //temp type
{

private T[] data; // array is of type ‘T’ where ‘T’ is the type parameter

public Queue()
{
this.data = new T[DEFAULTQUEUESIZE]; // use ‘T’ as the data type
}

public Queue(int size)
{

this.data = new T[size];

}

public void Enqueue(T item) // use ‘T’ as the type of the method parameter
{

}

public T Dequeue() // use ‘T’ as the type of the return value
{

T queueItem = this.data[this.tail]; // the data in the array is of type ‘T’

return queueItem;
}
}

then when you use the class it looks like this:
Queue<int> intQueue = new Queue<int>();  //replacing temp type with type int
Queue<Horse> horseQueue = new Queue<Horse>(); //replacing temp type with type Horse

—————————————————————————————-
references – are memory addresses passed to reffer to a variable
in C++ they are passed by using &variablename
in c# they are passed by using the keyword ref
shallow copy – fields are copied; if they are reference types, the reference will point to the original location
example:
public void swap(ref int x, ref int y)
{
int temp;

temp = x; /* save the value of x */
x = y;   /* put y into x */
y = temp; /* put temp into y */
}

when working with references this was the original variable is modified, they are not copies of the variable that are local to the function.

static void doIncrement(ref int param) // using ref
{
param++;
} static void Main()
{
int arg = 42;
doIncrement(ref arg); // using ref
Console.WriteLine(arg); // writes 43
}

——————————————————————–
NULL

int i = null; // illegal
int? i = null; // legal
if (i == null)

int? i = null;
int j = 99;
i = 100; // Copy a value type constant to a nullable type
i = j; // Copy a value type variable to a nullable type
j = i; // Illegal

int? i = 99;
Pass.Value(i); // Compiler error

pass value expects a regular int

The HasValue property indicates whether a nullable type
contains a value or is null, and you can retrieve the value of a non-null nullable type by reading the
Value property, like this:

int? i = null;

if (!i.HasValue)
{
// If i is null, then assign it the value 99
i = 99;
} else
{
// If i is not null, then display its value
Console.WriteLine(i.Value);
}

using uninitialized values in functions my using the out keyword.
When you pass an out parameter to a method, the method must
assign a value to it before it finishes or returns:

static void doInitialize(out int param)
{
param = 42; // Initialize param before finishing
}

—————————————————————————–
CASTING and BOXING:
casting is where you change the data type of something your working with.
boxing is when you make an object point to a variable which is on the stack, which inturn copies the variable into the heap
so after the “boxing” you are reffering to a seperate value stoed on the heap.
unboxing is where you reverse the process of something being copied to the heap and it is copied to the stack

not sure about the above but msdn says:
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type

int i = 42;
object o = i; // boxes
i = (int)o; // compiles okay (called unboxing)

checking wether the type of an object is what you expect it to be before casting using the “is” keyword:

WrappedInt wi = new WrappedInt();

object o = wi;
if (o is WrappedInt)
{
WrappedInt temp = (WrappedInt)o; // This is safe; o is a WrappedInt

}

using the “as” keyword:

WrappedInt wi = new WrappedInt();

object o = wi;
WrappedInt temp = o as WrappedInt;
if (temp != null)
{
… // Cast was successful
}
Like the is operator, the as operator takes an object and a type as its operands. The runtime attempts
to cast the object to the specified type. If the cast is successful, the result is returned and, in this
example, it is assigned to the WrappedInt variable temp. If the cast is unsuccessful, the as operator
evaluates to the null value and assigns that to temp instead.
—————————————————————————————————
POINTERS:

int * mypointer; //creates pointer to int
int a = 10;      //creates an int
mypointer = &a;  //points mypointer to memory address of “a”

you can modify the value at which a pointer points to by using * infront of the pointer:
*mypointer = 12;

—————————————————————————————————-
ENUMS:

enum Season { Spring, Summer, Fall, Winter }  // Spring = 0, Summer = 1, Fall = 2, Winter = 3
enum Season { Spring = 1, Summer =3, Fall, Winter } //an enum where you set the interger that a name equals. it counts up from the
last number used to Winter = 5.
enum Season : short { Spring, Summer, Fall, Winter } //sets the value type that the enums equal to the type short

Season colorful = Season.Fall;

enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}

class Demo
{
public static void Main()
{
System.Console.WriteLine(WeekDays.Sunday);
System.Console.WriteLine(WeekDays.Monday);
System.Console.WriteLine(WeekDays.Tuesday);
System.Console.WriteLine(WeekDays.Wednesday);
System.Console.WriteLine(WeekDays.Thursday);
System.Console.WriteLine(WeekDays.Friday);
System.Console.WriteLine(WeekDays.Saturday);
}
}

OUTPUT:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}

class Demo
{
public static void Main()
{
System.Console.WriteLine((int)WeekDays.Sunday);
System.Console.WriteLine((int)WeekDays.Monday);
System.Console.WriteLine((int)WeekDays.Tuesday);
System.Console.WriteLine((int)WeekDays.Wednesday);
System.Console.WriteLine((int)WeekDays.Thursday);
System.Console.WriteLine((int)WeekDays.Friday);
System.Console.WriteLine((int)WeekDays.Saturday);
}
}

OUTPUT:
0
1
2
3
4
5
6
————————————————————————————————————-
STRUCTS:
since the struct is held on the stack when you copy a struct to another you get a copy of the values not refrences of the values
The compiler-generated default constructor for a structure always
sets the fields to 0, false, or null—just as for a class.
so if you create a constructor it must take parameters
you cannot assign values to variables in the definition of a class, the constructor can do it, or you can once it is created.

struct Time
{
private int hours, minutes, seconds;

public Time(int hh, int mm, int ss)
{
this.hours = hh % 24;
this.minutes = mm % 60;
this.seconds = ss % 60;
}
public int Hours()
{
return this.hours;
}
}

Time now = new Time();  // create a time object NOT on the stack. fields are initialed to 0
Time now;               //create time object without calling the default constructor, fields ARE NOT initialized

structs are not objects but i did not know how to word it.

create a struct with a constructor which initializes hours and minutes by argument, seconds set to default of 0;
struct Time
{
private int hours, minutes, seconds;

public Time(int hh, int mm)
{
hours = hh;
minutes = mm;
seconds = 0;
}
}

Time now = new Time(12, 30); //creating the Time object and calling the constructor via arguments passed in
————————————————————————————————————–
ARRAYS

int[] pins; // Personal Identification Numbers
pins = new int[4];
int[] pins = new int[4]{ 9, 3, 7, 2 };  //initializing the array when creating it
int[] pins = { 9, 3, 7, 2 };
myPin = pins[2];  //accessing element 3 in an array (count starts at 0)
pins[2] = 1234;   //setting  element 3 in an array (count starts at 0)

iterating through an array:
int[] pins = { 9, 3, 7, 2 };
for (int index = 0; index < pins.Length; index++)
{
int pin = pins[index];
Console.WriteLine(pin);
}

returning an array via return keyword:

public int[] ReadData()   //notice the [] and the function name is ReadData
{
Console.WriteLine(“How many elements?”);
string reply = Console.ReadLine();
int numElements = int.Parse(reply);
int[] data = new int[numElements];
for (int i = 0; i < numElements; i++)
{
Console.WriteLine(“Enter data for element {0}”, i);
reply = Console.ReadLine();
int elementData = int.Parse(reply);
data[i] = elementData;
}
return data;
}

take the returned array and assign it to an array variable:
int[] data = ReadData();    //calls function ReadData() and takes what is returned and puts it in its array

COPYING ONE ARRAY TO ANOTHER:
since arrays are on the heap you need to copy element by element like shown:

int[] pins = { 9, 3, 7, 2 };
int[] copy = new int[pins.Length];
for (int i = 0; i < pins.Length; i++)
{
copy[i] = pins[i];
}

MUTIDIMENSIONAL ARRAYS:

int[,] items = new int[4, 6];   // create array which is mutidimensional aith 24 buckets
items[2, 3] = 99;          // set the element at cell(2,3) to 99
items[2, 4] = items [2,3]; // copy the element in cell(2, 3) to cell(2, 4)
items[2, 4]++;             // increment the integer value at cell(2, 4)

There is no limit on the number of dimensions that you can specify for an array.
int[, ,] cube = new int[5, 5, 5];
cube[1, 2, 1] = 101;
cube[1, 2, 2] = cube[1, 2, 1] * 3;

UN-UNIFORM MUTIDIMENSIONAL ARRAYS.
these array have different columns for different rows. the array is not even.

int[][] items = new int[4][];      //create initial array
int[] columnForRow0 = new int[3];  //create another array
int[] columnForRow1 = new int[10]; //create another array
int[] columnForRow2 = new int[40]; //create another array
int[] columnForRow3 = new int[25]; //create another array
items[0] = columnForRow0;          //assign coloumn to existing array
items[1] = columnForRow1;          //assign coloumn to existing array
items[2] = columnForRow2;          //assign coloumn to existing array
items[3] = columnForRow3;          //assign coloumn to existing array
——————————————————————————————————–
working with the values passed to main on the commandline:
static void Main(string[] args)
{
foreach (string filename in args)
{
ProcessFile(filename);
}
}
———————————————————————————————————
PASSING A PARAMETER ARRAY TO A FUNCTION:
A params array must be the last parameter
A non-params method always takes priority over a params method

class Util
{
public static int Min(params int[] paramList) //parameter list passed in as an argument
{
// code exactly as before
}
}

You can pass the Black.Hole method arguments of different types, and these arguments will
automatically be wrapped inside an object array:

class Black
{
public static void Hole(params object [] paramList)

}
—————————————————————————————-
ACCESSING THE BINARY VALUE STORED BY AN INT
the NOT “~” operator performs a binary NOT
the left-shift “<<” operator shift all binary digits one place to the left
the OR “|” operator performs a bitwise or operation
the AND operator “&” performs a bitwise AND
the XOR “^” operator performs a bitwise exclusive OR operation

—————————————————————————————-
INDEXERS:
turns a class into an array type of thingy.
two values are used to manage data. [index] for the number of the bucket
“value” for the value that is set for that index.
you access and set values by creating an object which contains the indexer
so like  SpellingList myList = new SpellingList();
then you can access the indexer like follows:
myList[5] = “was”;

Declaring Indexer

1: // indx2.cs – Using an indexer
2: //————————————————–
3:
4: using System;
5:
6: public class SpellingList
7: {
8: protected string[] words = new string[size];
9: static public int size = 10;
10:
11: public SpellingList()
12: {
13: for (int x = 0; x < size; x++ )
14: words[x] = String.Format(“Word{0}”, x);
15: }
16:
17: public string this[int index]
18: {
19: get
20: {
21: string tmp;
22:
23: if( index >= 0 && index <= size-1 )
24: tmp = words[index];
25: else
26: tmp = “”;
27:
28: return ( tmp );
29: }
30: set
31: {
32: if( index >= 0 && index <= size-1 )
33: words[index] = value;
34: }
35: }
36: }
37:
38: public class TestApp
39: {
40: public static void Main()
41: {
42: SpellingList myList = new SpellingList();
43:
44: myList[3] = “=====”;
45: myList[4] = “Brad”;
46: myList[5] = “was”;
47: myList[6] = “Here!”;
48: myList[7] = “=====”;
49:
50: for ( int x = 0; x < SpellingList.size; x++ )
51: Console.WriteLine(myList[x]);
52: }
53: }

indexers with interfaces:
You can declare indexers in an interface. To do this, specify the get keyword, the set keyword, or
both, but replace the body of the get or set accessor with a semicolon. Any class or structure that
implements the interface must implement the indexer accessors declared in the interface

interface IRawInt
{
bool this [ int index ] { get; set; }
} struct RawInt :
IRawInt
{

public bool this [ int index ]
{
get { … }
set { … }
}

}
——————————————————————
Resizable array type thingy with LISTS:

List<int> list = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
list.Add(value);  //will add a new element if needed
}

// You can convert it back to an array if you would like to
int[] terms = list.ToArray();

Leave a Reply