Thursday, May 08, 2014

.Net var (C#) Almost Everywhere, One Exception

Starting from .Net 3.0, Microsoft introduced type var in C#, as a simply way to binding strongly type. This is a very convenient way to define variables. Basically, .Net will be smart enough to infer correctly data type. It makes code maintenance and update much easy and no need to change data type in case variable types changed. I like it very much and use var almost everywhere.

However, recently I found one case this var is not able to infer explicit data type. In the case of dynamic delegate, you have to use explicit delegate type:


var myDelegate = delegate(int valueA, int valueB) { return valueA + valueB; };

.Net cannot infer what delegate type is for myDelegate. You have to use the explicit delegate type in this case:

delegate int SumOfTwoValues(int v1, int v2);
SumOfTwoValues myDelegate = delegate(int valueA, int valueB) { return valueA + valueB; };


I found this interesting exception when I was sharing my knowledge about delegate with my co-worker.

0 comments: