Why can't c# use inline anonymous lambdas or delegates? [duplicate]
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
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.