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”

}

}

}

No comments: