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

Yan Cui

I help clients go faster for less using serverless technologies.

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..


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *