Trivia Friday

Everybody loves a cliffhanger, right?  I found myself needing to write the following code the other day:

public static class ExpressionExtensions
{
    public static Expression<Func<T, TResult>> Expr<T, TResult>(
        this T item, 
        Expression<Func<T, TResult>> expr)
    {
        return expr;
    }
}

Why would I want to write something like this, which seems to do absolutely nothing?  One hint – it’s not because I wanted a clever, more terse way to declare an expression, although it does have that effect.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in C#. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://theoldsewingfactory.com Rob White

    Is it a casting thing? If you explicitly specify T then possibly you can get type coercion where simply casting one expression to another type in the same inheritance heierachy might fail.

  • Jason Meckley

    reduce angle brackets

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Rob

    Getting warmer…

    @Jason

    Not intentionally, but I did find that it’s a nice side effect

  • http://thinkbeforecoding.com thinkbeforecoding

    Using this code, you can
    declare a var that will receive the expression instead of declaring it with Expression>
    ensure that that expression input is of expected type, without having to give lambda parameter type…

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @thinkbeforecoding

    Nice side effect, but check my hint – it’s not directly what I was trying to achieve.

  • http://devlicio.us/blogs/christopher_bennage/ Christopher Bennage

    So you can convert a lamda into an expression explicitly.

  • http://www.jeremyskinner.co.uk Jeremy Skinner

    I’m guessing so you can get a reference to an expression for a property on an anonymous type. Because you can’t declare the type directly, this will allow type inference to kick in.

  • Omer Mor

    So you could declare expressions that take anonymous types?

  • Harry

    You can write something like:

    42.Expr(x => x * x)

    and thus do not have to specify T or TResult

  • Mikael Östberg

    + 1 on the anonymous type or any type for that matter.

    var anon = new {Number = 1};
    var expr = anon.Expr(a => a.Number + 1);

  • Benjamin Wegman

    So you can do something like this:

    var expr = this.Expr(x => x + “Test”);

    And have implicit typing of the expression?

  • http://www.lostechies.com/members/bogardj/default.aspx bogardj

    @Jeremy Omer and Mikael

    ding ding ding you are correct!