Generics are available in most programming languages which are currently used by developers. In this post we will dig into details of the C# language. We will also check how they differ from Java and C++ implementation.
When the C# was released in 2002, it did not contain generics. This could also be called “generic-free world”. In that time, a developer had to apply casting when he was using collections such as ArrayList. Sometimes that led to exceptions which either stopped the application or had to be wrapped in try/catch clauses. But more importantly, casting was influencing the performance, which in my opinion, put forward the biggest argument to introduce generics in the next version of the C# framework.
During that time we had to use an object as either a parameter or return type in almost every place. This is bad – like Jon Skeet says – it’s “bad in a necessary evil kind of way”. At some point you will simply need to do the casting – and that is just bad.
I think it’s very important to know what is going on out there in the universe. However, before we dig into details about the C# implementation of generics, let’s see how other languages implemented them or emulated such behavior.
In C++ there are no generics, there are templates. In a nutshell, they are macros on steroids.
When a particular type is used in C++, the compiler for that particular type parameter generates appropriate code. The compiler will change all the places where the type parameter is used and will change it to the used type for creation of a template. The compiler creates the type only once – so using the same type again is going to apply the same code. This means that there can be a great output library size increase because of that – we will just have more types (as we will see, this is quite more clever in CLR).
One of the biggest advantages of the C# implementation, which the templates have, is the fact that the type parameter does not have to be just type names. We can use function names, variable names or even constant expressions (e.g. 20). This is a very interesting feature which I sometimes miss in C# (but very rarely ).
Object = one (ring?) to rule them all.
This is all that JVM knows about a particular object (ok, there is some metadata to describe a type as generic in the bytecode before compilation) that it is generic.
This is great example from Skeet book (which I highly recommend – C# in depth is just must-read position if you are C# developer!) – if it only compiled
and this one
Both of these codes would, in fact, generate the same bytecode – just because of Java’s feature which is called type erasure. As it is described in the documentation – it is applied by the compiler to implement generics. This just replaces all the type parameters in generic types, insert type casts where necessary and generate bridge methods to preserve polymorphism in extended generic types.
Why?! This is a normal question at this point. I think that the main reason is the back-compatibility. Even from the new code with generics you are able to run your application on an older runtime. This is not possible in C# 2.0 – your application just won’t start on CLR 1.1. Another interesting feature, which can be missing in C#, is the generic variance. Through it you are can form something like this:
I wish I could describe more languages and their generics implementation and I hope I can extend this in the future. If any of you have any interesting information – please leave a comment.
Microsoft presented a new version of a language in a pack with Visual Studio 2005 and .NET Framework 2.0. One of the most important features introduced by the new version were generics. You may also remember that in 2005 we received partial classes from MS, anonymous methods, a yield keyword and thanks to generics we got Nullable types as well.
Using System.Object does not only cost the runtime to perform casting, but also when you keep your value type as an object – there is boxing involved. And you probably know very well that this causes a lot of operations – when saving (there is boxing), and when you retrieve value from the collection – there is unboxing. The JIT can treat value types, so there is no boxing and unboxing involved!
There is not much improvement in performance for reference types. Though this was also slightly improved, you probably won’t see much improvement in your application just by changing the type to the generic one.
Thanks to generics we got compile checks – so the safety of our programs increased. But did we get…
This question was on my mind for quite a long time. And I am not sure how many bugs in applications were caused by the wrong casting. I talked to a couple of people in my company and we agreed that this is not the greatest output programming the world got from generics. It’s undoubtedly true, but we should not treat generics as a solution for a programmer’s lack of knowledge, experience and time.
When you use generics in your code it is very often more self-explanatory than the non-generic version. Sometimes we just call our collection list or set and without a comment (which very often goes out-of-date very soon) or deeper analysis it is not easy to recognize its purpose. Thanks to generics the IDE support is also possible.
Ok, finally we can see how it looks like:
There are several ways you can declare a type:
I have presented three different ways of declaring a list. At first glance they would all give us the same.
To be honest, only the 1st and 2nd will give us *exactly* the same result – var is just removed during a compilation time and changed by the type itself. It does not cause any performance overhead during runtime – you can use it.
In my opinion, the best option is the third one where you use an interface type – I will prepare another post about this behavior, and since I’ve seen so many developers using the first one, I need to give it more focused attention. In brief, you will be able to assign any other type which implements IList to list3 – for example your own type. When using the 1st – such a possibility does not exist.
It is very usual that you want to call a method of the generic type – to do that you must define what that type is. You can do that by type constraints – where you force the type to fulfill the constraint.
There are three types of constraints:
1. The first type of constraint ensures that the type is either reference or value type. To say that the type is a reference type you just set where T : class. The twin constraint is T : struct – where you ensure that the generic is a value type.
2. The second and most encountered by me is the constructor type constraint. In this one you just order that the type must have a parameterless constructor. The only thing you need to remember while using this one is that it must be the last constraint for any particular type parameter.
3. This one is, of course, the most complicated of constraint types– where you ensure that a type can be converted to another type (or in other words – that your generic type implements a specific base class or interface). There is also another interesting (let’s call it a sub-type) feature – that your generic type can be converted to another type argument – this is called a type parameter constraint. I often find this one difficult to understand, but after a while with playing around this comes very handy. Here are couple of samples:
These are very easy cases of the conversion type constraint – but you probably already got it. In the future I will dig into the details about these constraint types – because I sometimes receive questions from developers in my company regarding these types of parameter constraints (these are probably harder to understand).
Why do we even care if the new() constraint should be the last one?! Here’s what the answer is – it can just frequently save you a lot of time. Of course this simple one is caught by the compiler with a correct error message:
But you need to remember – that not all of these cases are so easy to spot. And what is also more important – you will need no compiler to design your class on a whiteboard correctly and talk to your peers.
Let’s see an example when you work with arrays. Let’s say that you have a hierarchy of fruits – where you have a class Fruit and two derivatives from that – Apple and Banana.
Thanks to polymorphism this would work correctly – the runtime will have the information about the banana as the fruit. And this will be resolved correctly.
But hey – if it works correctly on the types, maybe we could do the same with arrays, right? You probably would like to be able to do that:
All of this works fine – up to this point. But you have already imagined an example when you just try to assign a banana as the first element of fruits. This will case the ArrayTypeMismatchException. There is a special IL method which checks whether you assign the correct type to the array.
OK, so for five years there were no changes in the generics. But when the version C# 4.0 came into the light, there were some changes in the generics implementation. Microsoft introduced covariance and contravariance to the language – everything thanks to two additional keywords – in and out.
When you think variance you should think – possibility to use an object as one type, as if it was another, but always in a type-safe way. You are used to that – but you probably never heard of it by such a name – for example when you should return BaseTypeClassand you return SomeDerivedClass instead. In case of generics, things get a little bit more complicated – because this is not the type, but the type parameters on which the variance is applied.
Every book, blog post or any other kind of an article about the variance starts with the covariance – probably because this one is just easier to understand as it seems to be more natural for us.
Covariance means that the value is being returned from an operation back to the caller. One of the most commonly used examples of the covariant type is IEnumerable<T>. When you check the implementation you will see this:
There is one particular thing you should look at – the out keyword. By setting this keyword you guarantee that the type parameter is returned only by your API. Thanks to that you are able to make such an operation:
And everything will work as usually thanks to the improved implementation of the language and runtime. Nothing will be broken, because the base collection (managers) will never be changed – because it is OUT-going parameter.
As you probably have guessed – the other way around is the cotravariance where the type goes IN-to the type. That is why the keyword in is used for these types. One of the most used example of the contravariant class is
As you can see, the contravariant IComparable<T> is marked with inkeyword – this means that API is consuming the values instead of producing them.
Now you probably understand why it is called contra-variant – because it is contrary to the usual derivation direction.
You probably ask – why are the two additional keywords even introduced – and the compiler is able to derive that information directly from the source code. I think that you should consider two things when you think about that:
1. We are all humans and the more we express our ideas, the easier another person (or even ourselves in the future!) will understand. By looking at the source code you don’t have to think whether it is contravariant, covariant or even invariant (which means that it goes both ways and we cannot mark it either way!).
2. It is easy to add another method into the class (interface) which could probably break some code using it. By having these keywords you will see that by changing that, you are making breaking change by making something invariant. And that’s something we don’t want to do – break some code we are not aware of (either in our own implementation or even worse, in the client who uses our API!).
The topic of contra- and covariance is so broad that it requires more attention, so you can expect another blog post about it in the future.
As you have seen – generics gives C# very much. I have only covered the most important parts. Some of them need more detailed attention and this is what I would like to do – prepare shorter posts in which I will dive into more details for some cool features the generics have.
This whole post is based on my presentation I created for my colleagues. I wanted to share it with you and I hope you found this more interesting than just a plain text you usually see on the programming blog.
FYI: I do not have rights to the pictures and photos which you can see.