Search:

Custom Search
_________________________________________________________________

Friday, February 15, 2008

Generics in c#

Generic allows declaring classes, methods, interfaces, etc without specify the type of value you are going to store. You have to specify the type of value you are going to use when you declare the instance to be used. So when you do that, the generic T value is replaces with the actual type you are going to use at compilation time. See the next example to get the idea better:

//Generics.cs

namespace ConsoleApplication1

{

public class Generics

{

public T value;

}

}

//Program.cs (main)

namespace ConsoleApplication1

{

public class Program

{

public static void Main(string[] args)

{

Generics<String> g = new Generics<string>();

g.value = "String value";

//g.value = 66; Compilation Error

Console.WriteLine(g.value.ToString());

//Will show: “String value”

}

}

}

Friday, February 8, 2008

Simple Methods using Lists (c#).

This method steps over each element of the list and calculates the total (just an integer value located in the class Component).

private List<Component> list = new List<Component>();

public int total()

{

int total = 0;

foreach (Component c in this.List)

{

total = total + c.totalH();

}

return total;

}

Now, if you want to find something on that list but you don’t want to step over every single element of the list (to stop when the “something” was found) you need to add the break expression.

foreach (Component c in this.List)

{

if (c.id == 5)

{

List.Remove(c);

break;

}

}