Frage

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#?

War es hilfreich?

Lösung

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:

Func<string, string> moo = x => x.ToString();

If you really want to still use var, you can do something like this:

var moo = new Func<string, string>(x => x.ToString());

Andere Tipps

You don't need to specify parameter type in lambda expressions, just do the following:

Func<string, string> moo = (x) => x.ToString();
Func<string, string> moo = (x) => x.ToString();

With var C# doesn't know if you want a Func and Action or something else.

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;

 Func<string, string> moo = (string x) => x.ToString();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top