Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an anonymous class have a lambda property, but it can have a Func<> property? [duplicate]

Tags:

c#

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?

like image 451
Stephen Gross Avatar asked Nov 14 '11 21:11

Stephen Gross


1 Answers

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.

like image 64
Thomas Levesque Avatar answered Nov 09 '22 09:11

Thomas Levesque