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

In C#, it’s pos­si­ble to com­bine two del­e­gates, A and B to cre­ate a new mul­ti­cast del­e­gate, C:

image image 

When the mul­ti­cast del­e­gate is exe­cut­ed, the com­bined del­e­gates are exe­cut­ed in order as you can see from the exam­ple above. But before you can start mix and match­ing your del­e­gates like a kid in a can­dy store, there is how­ev­er, the small mat­ter of hav­ing to keep the CLR hap­py. You see, only del­e­gates of the same type can be com­bined, but and this is a BIG but, it is a run­time require­ment that is not in line with the covari­ance sup­port in C# 4.

For instance, this is legal in C# 4:

image

As far as the com­pil­er is con­cerned this is fine, and it builds and runs, but when you try to invoke the mul­ti­cast del­e­gate you will get a run­time excep­tion warn­ing you that the del­e­gates must be of the same type..