In C#, What is <T> After a Method Declaration?

Drew picture Drew · Apr 30, 2010 · Viewed 39.5k times · Source

I'm a VB.Net guy. (because I have to be, because the person who signs my check says so. :P) I grew up in Java and I don't generally struggle to read or write in C# when I get the chance. I came across some syntax today that I have never seen, and that I can't seem to figure out.

In the following method declaration, what does < T > represent?

static void Foo < T >(params T[] x)

I have seen used in conjunction with declaring generic collections and things, but I can't for the life of me figure out what it does for this method.

In case it matters, I came across it when thinking about some C# brain teasers. The sixth teaser contains the entire code snippet.

Answer

Pranay Rana picture Pranay Rana · Apr 30, 2010

what you are asking is the concept of the generics in c#. By using generics you can use this method for the types you want

suppose you have to create a function to add two numbers. In that case, your function is

//For integer :
public int sum(int a, int b)
{ 
  return a + b;
}



//For floating point numbers :
public float sum( float a, float b)
{
  return a + b;
}

Following this logic, if you want a function that will sum two double type numbers you would create one more function, and so on.

Note: code above will not work with C#, but it for explaining concept easily, it just sudo code it will work with C# if you have nullable type or reference type easily or one need to write logic to convert value to primary type.

Bu with the help of generics you can replace all of these functions and write the following,

public T sum<T>(T a, T b)
{
  return a + b;
}

This will work for all numeric types, as well as for strings.

check this out for more detail : http://www.codeproject.com/kb/books/EssentialCS20.aspx