What is the equivalent C# code for the following VB.NET:
Dim moo = Function(x as String) x.ToString()
I thought that this should work:
var moo = (string x) => x.ToString();
but that yielded a compiler error: Cannot assign lamda expression to an implicitly-typed local variable
After some further investigation, I discovered that the type of the variable moo
(moo.GetType()
) in the VB example is VB$AnonymousDelegate_0'2[System.String,System.String]
Is there anything equivalent to this in C#?
The lambda needs to infer the type of the delegate used from its context. An implicitly typed variable will infer its type from what is assigned to it. They are each trying to infer their type from the other. You need to explicitly use the type somewhere.
There are lots of delegates that can have the signature that you're using. The compiler needs some way of knowing which one to use.
The easiest option is to use:
If you really want to still use
var
, you can do something like this:You don't need to specify parameter type in lambda expressions, just do the following:
The problem is that you can't use implicit typing for delegates. Meaning the
var
on the LHS is the actual cause of the issue, your lambda expression is fine. If you change it to the following it will compile and work as expected;With
var
C# doesn't know if you want aFunc
andAction
or something else.