Hacker News new | ask | show | jobs
by oozcitak 5725 days ago
I would say expression trees is one of the less well-known and under-appreciated features of C# 3.0:

    Expression<Func<int, int>> e = (x) => x + 1;
    Func<int, int> f = e.Compile();
    int b = f.Invoke(42);
1 comments

I'm quite fond of C# but that syntax is a bit much when compared to things like humble old JavaScript:

   var f = function(x) { return x + 1; };
   var b = f(42);
The Expression tree part is powerful (you can inspect it with code, pull property names out, etc), but it's not needed in most cases. Your example in C# is:

  Func<int, int> f = x => x + 1;
  int b = f(42);
This is shorter than the JavaScript. The C# is more verbose where has to specify a type for f because it cannot work it out from context (in fact the left side of the '=' supplies type information to the right side), but the actual expression on the right is less verbose than the JavaScript with its "function" and "return" keywords.

If you want, the second line can be

  var b = f(42);
But it's the same number of chars. I don't think that you gain anything from letting the compiler work out that b is an int.
The best thing about expression trees isn't that it lets you declare a method like Func<Func<int>, int> = ... (or whatever), but that you can inspect (and modify) the expression tree at runtime. This is what powers LINQ, and the 'static reflection' used by fluent APIs like Fluent nHibernate.
well you can write it as

  var f = ((x) => x + 1).Compile();
  int b = f.Invoke(42);
I don't think that would work. How would the compiler know the type of x and the return type of the lambda expression?
It won't. In just about all cases, C# doesn't do backtracking to infer types. See Eric Lippert's posts: http://blogs.msdn.com/b/ericlippert/archive/2010/10/04/no-ba...