Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't c# use inline anonymous lambdas or delegates? [duplicate]

I hope I worded the title of my question appropriately.

In c# I can use lambdas (as delegates), or the older delegate syntax to do this:

Func<string> fnHello = () => "hello"; Console.WriteLine(fnHello());  Func<string> fnHello2 = delegate() {     return "hello 2"; }; Console.WriteLine(fnHello2()); 

So why can't I "inline" the lambda or the delegate body, and avoid capturing it in a named variable (making it anonymous)?

// Inline anonymous lambda not allowed Console.WriteLine(     (() => "hello inline lambda")() );  // Inline anonymous delegate not allowed Console.WriteLine(     (delegate() { return "hello inline delegate"; })() ); 

An example that works in javascript (just for comparison) is:

alert(     (function(){ return "hello inline anonymous function from javascript"; })() ); 

Which produces the expected alert box.

UPDATE: It seems you can have an inline anonymous lambda in C#, if you cast appropriately, but the amount of ()'s starts to make it unruly.

// Inline anonymous lambda with appropriate cast IS allowed Console.WriteLine(     ((Func<string>)(() => "hello inline anonymous lambda"))() ); 

Perhaps the compiler can't infer the sig of the anonymous delegate to know which Console.WriteLine() you're trying to call? Does anyone know why this specific cast is required?

like image 617
Samuel Meacham Avatar asked Apr 22 '10 02:04

Samuel Meacham


2 Answers

Lambdas in C# do not have types, until they are used in a context that casts them to a delegate or Expression type. That's why you can't say

var x = () => "some lambda"; 

You might enjoy

http://blogs.msdn.com/ericlippert/archive/2007/01/11/lambda-expressions-vs-anonymous-methods-part-two.aspx

http://blogs.msdn.com/ericlippert/archive/2007/01/12/lambda-expressions-vs-anonymous-methods-part-three.aspx

like image 168
Brian Avatar answered Oct 01 '22 03:10

Brian


It seems to work if you give it a type cast:

String s = ((Func<String>) (() => "hello inline lambda"))(); 

Is it useless? Not entirely. Take the below:

String s; {     Object o = MightBeNull();     s = o == null ? "Default value" : o.ToString(); } 

Now consider this:

String S = ((Func<Object,String>)(o => o == null ? "Default value" : o.ToString())     )(MightBeNull()); 

It's a little ugly, but it is compact.

like image 23
sopatt Avatar answered Oct 01 '22 02:10

sopatt