In C#, it’s possible to combine two delegates, A and B to create a new multicast delegate, C:
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:
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..
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.

Hi, my name is Yan Cui. I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.
Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.
The post .Net Tips – Make sure the runtime types match when combining delegates appeared first on theburningmonk.com.