I’m trying to learn C#’s restrictions on an anonymous type. Consider the following code:
var myAwesomeObject = new {
fn1 = new Func<int>(() => { return 5; }),
fn2 = () => { return 5; }
};
So we’ve got two properties that are actually functions:
fn1: AFunc<int>that returns5.fn2: A lambda function that returns5.
The C# compiler is happy to work with fn1, but complains about fn2 :
cannot assign lambda expression to anonymous type property.
Can someone explain why one is ok but the other is not?
Because there is no way for the compiler to know the type of
() => { return 5; }; it could be aFunc<int>, but it could also be any other delegate with the same signature (it could also be an expression tree). That’s why you have to specify the type explicitly.