Thursday, August 6, 2009

Passing a generic as a parameter to a method in C#

The syntax for generics can be a little strange until you get used to. I am still getting used to some parts of it. :) Maybe you want to write a method that takes a generic type as a parameter, but you don’t want to lock down what the type for the generic is. What we are talking about is Generic Type Parameters. You can even have multiple Type Parameters.

I think the best way to describe what I am talking about is to show an example.

private void MyMethod1(Array myArray)
{
// do something with the array here.
}


private void MyMethod2(List<int> myArray)
{
// do something with the generic array here.
}

private void MyMethod3<T>(List<T> myArray)
{
// do something with the generic array here.
}

private void MyMethod4<TMyTypeA, TMyTypeB>(List<TMyTypeA> myArray, List<TMyTypeB> myArray2)
{
// do something with the generic array of type a here.
// do something with the generic array of type b here.
}

private void ExampleCallingMethod()
{
// nothing fancy here
Array array1 = "a,b,c".Split(',');
MyMethod1(array1);

// nice if you know you always want to accept a list of ints
List<int> intArray = new List<int> { 1, 2, 3 };
MyMethod2(intArray);

// nice if you want to accept a list of any kind of objects
// For example ints or strings
MyMethod3<int>(intArray);
MyMethod3(intArray);


List<string> strArray = new List<string> { "a", "b", "c" };
MyMethod3<string>(strArray);
MyMethod3(strArray);

// nice if you have to accept (in this case) two lists of any kinds of objects
MyMethod4<string, int>(strArray, intArray);
MyMethod4(strArray, intArray);
}
In the above examples you can see that <T> is used as a Type Parameter. It is a placeholder for whatever type is passed to the Generic List. <T> is not a key word, but more a naming convention. The surrounding <> is important though. As described here (Generic Type Parameters) it is convention to prefix the name of a Type Parameter with a capital T. For example, TMyTypeA or TMyTypeB. It also seems to be convention to just use <T> if there is only one Type Parameter.
In the case where you don’t want to accept any type, but still want to use Generics, you can restrict the types that can be passed as described on this (Constraints on Type Parameters) page.
For other related topics on programming Generics, check out: Generics Programming Guide.

No comments: