Thursday, December 10, 2015

Generics in C#

Generics were introduced in C# 2.0 and were the most powerful feature of C# 2 at that time. They allow type and method parameterization in terms of the types they interact with.

Generics

Generics allow classes and methods to have more functionality as compared to what they could do without generics. In order to understand their power, let's take a look at some code without generics. We will then apply generics and see how they can help us.

Suppose, we have a simple method like this:

private static bool AreEqual(int a, int b)
{
     return a == b;
}

We can use this method in our code anywhere:

var x = AreEqual(10, 11);

It works fine as long as the application is limited to use only integers. Suppose, we want to use another type, for e.g. string for similar method. In order to do that, we will have two options (pre C# 2.0):
i) Create a new method AreEqual() which takes string arguments,
ii) Change AreEqual() method to have parameters of type object.

First solution will lead to code duplication for each and every newly added type.
Second solution will lead to casting of the objects each and every time, which might lead to performance issues. Also, by casting to object, we loose compile time type safety which may lead to run-time exceptions.

So now let's take a look at how we can simplify it using generics:

private static bool AreEqualGeneric<T>(T a, T b)
{
     return a.Equals(b);
}

So now we can use the generic method like this:
var y = AreEqualGeneric<int>(11, 11);

var z = AreEqualGeneric<string>("A", "B");

As you can see we are able to use the same method with different parameter types. So now we are able to write generic code one-time as well as have compile time type safety.

Conclusion

We saw how generics help us decouple logic from data type. In future posts, I will be covering some more on generics in C#.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


No comments:

Post a Comment