Friday, July 18, 2008

Don't be afraid of Generics in C#

I have been really slow to start using Generics and I have been even slow about writing my own methods that make use of Generics in C# (.NET 2.0 or newer). Today I realized exactly how easy it is to write a very generic method and have it use any type you want it to. This is of course the beauty of Generics. Without rambling anymore about my reluctance, here is how you do it. Let's assume that you are writing a bunch of methods that are all the same except they take different type of objects or even primitives as parameters. Here is a simple example of what you could write for each type you want: public static void AreEqual(int a, int b) { return a.Equals(b); } public static void AreEqual(string a, string b) { return a.Equals(b); } This is trivial example where the logic of the code is VERY simple. Imagine if that was a complex algorithm like searching or sorting. Would you really want to have that logic duplicated for each type that you want to work with. Of course not. Again, the prime reason for using Generics. Here is what you could write using Generics (Write once for ALL types): public static void AreEqual<T>(T a, T b) { return a.Equals(b); } You'll notice it looks very similar to the non-generic code except that it uses T instead of a type that you are used to. T is a special placeholder for what type the calling code wants it to be. Here is how you would call the non-generic code: bool retval = AreEqual(1, 0); bool retval = AreEqual("xxx", "yyy"); Here is how you could call the generic code: bool retval = AreEqual<int>(1,0); bool retval = AreEqual<string>("xxx", "yyy"); The syntax is a little strange at first in the end I find it very easy to use. It helped me to think of it as a runtime search and replace of 'T' with the type I currently want to use.

2 comments:

Anonymous said...

Thanks, I got the concept of generic method.

Brent V said...

Glad to help. Thank you for the feedback.