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
: A Func<int>
that returns 5
.fn2
: A lambda function that returns 5
.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 a Func<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With