by MatthewPhillips · 13y ago · 0 comments
(new Func<string>(() =>
{
return "foo";
}))();
That's pretty awful and as a result you rarely see anyone doing stuff like that, whereas with JavaScript it's used regularly. But for C# it's another checkbox that they can say they support.C# should stick with trying to be the best statically typed compiled object oriented language.
() => "foo"
Please don't participate in a conversation if you aren't willing to spend the time necessary to gain a baseline level of understanding of the topic.That it simply returns a string with no logic and therefore can be written slightly simpler belays the point I was making. You simply don't see this type of code being used much in C# because it isn't idiomatic, yet it exists to mark off a checkbox.
var func = () => "foo";
func();
As far as "you don't see this type of code being used much", that's just patently false. Anonymous functions (particularly predicates) are the whole way you interact with LINQ.So I'll ask this: what's the equivalent example in Java?
Expression<Func<string>> func = () => "foo";
func.Compile()();
That's hardly better, and it's still not anonymous! You probably like Lambda Expressions because they make things like LINQ elegant, and indeed they do. But a lambda expression is confusingly similar looking to a func (indeed a mistake you made) but when you try to do something more complicated like this: Expression<Func<string>> func = () =>
{
string foo = "bar";
return foo;
};
That won't compile because a lambda expression can't have a statement body, it can only contain (a single!) expression.Now the cool thing about lambda expressions is that to the end user they are simple and elegant assuming you know that they are not the same thing as functions, but on the other end of it; consuming a lambda expression you get to see the guts of it and realize what a hack it is on the language. Sure, in the context of a compiled statically typed language it's rather powerful. It's how they are able to compile a lambda expression into a SQL statement, because you can inspect lambda expressions which you can't do to functions.
Now you asked about Java and I'm not going to defend Java or predict what their intentions are, but I'll just say that Java is being much more conservation about sticking to what it is; a statically typed compiled language. C# is attemping to be everything to every body.
new Func<string>(()=>"foo")();
(function(){return "foo";})();
Oh look - exactly the same number of characters. How awful. ()=>"foo"
?