Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value with anonymous method?

Tags:

c#

.net

lambda

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?

like image 424
4thSpace Avatar asked May 09 '12 17:05

4thSpace


People also ask

Can an anonymous function return a value?

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.

Can I return a method in C#?

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.

What is anonymous method in C# with example?

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.


1 Answers

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")(); 
like image 103
JaredPar Avatar answered Oct 10 '22 00:10

JaredPar