.Net Tips – Make sure the runtime types match when combining delegates

In C#, it’s possible to combine two delegates, A and B to create a new multicast delegate, C:

image image 

When the multicast delegate is executed, the combined delegates are executed in order as you can see from the example above. But before you can start mix and matching your delegates like a kid in a candy store, there is however, the small matter of having to keep the CLR happy. You see, only delegates of the same type can be combined, but and this is a BIG but, it is a runtime requirement that is not in line with the covariance support in C# 4.

For instance, this is legal in C# 4:

image

As far as the compiler is concerned this is fine, and it builds and runs, but when you try to invoke the multicast delegate you will get a runtime exception warning you that the delegates must be of the same type..