This fails
string temp = () => {return "test";};
with the error
Cannot convert lambda expression to type 'string' because it is not a delegate type
What does the error mean and how can I resolve it?
Also, we create anonymous functions in JavaScript, where we want to use functions as values. In other words, we can store the value returned by an anonymous function in a variable. In the above example, we stored the value returned by the function in the variable variableName.
In C#, a method can return any type of data including objects. In other words, methods are allowed to return objects without any compile time error.
The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn't require a name and return type. Hence we can say, an anonymous method has the only body without a name, optional parameters and return type.
The problem here is that you've defined an anonymous method which returns a string
but are trying to assign it directly to a string
. It's an expression which when invoked produces a string
it's not directly a string
. It needs to be assigned to a compatible delegate type. In this case the easiest choice is Func<string>
Func<string> temp = () => {return "test";};
This can be done in one line by a bit of casting or using the delegate constructor to establish the type of the lambda followed by an invocation.
string temp = ((Func<string>)(() => { return "test"; }))(); string temp = new Func<string>(() => { return "test"; })();
Note: Both samples could be shorted to the expression form which lacks the { return ... }
Func<string> temp = () => "test"; string temp = ((Func<string>)(() => "test"))(); string temp = new Func<string>(() => "test")();
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