Nathan Evans' Nemesis of the Moment

Why doesn’t C# support lambdas for properties?

Posted in .NET Framework by Nathan B. Evans on February 1, 2012

Any time I write a C# property these days I can’t help thinking to myself how they would be so much cleaner if they supported a (syntactically restricted) form of lambda expression on both the getter and setter.

Consider this:

public DateTime Timestamp {
    get {
        return Settings.Default.Timestamp;
    }
    set {
        Settings.Default.Timestamp = value;
        Settings.Default.Save();
    }
}

Would you agree that it looks cleaner like the following?

public DateTime Timestamp {
    get => Settings.Default.Timestamp;
    set => {
        Settings.Default.Timestamp = value;
        Settings.Default.Save();
    }
}

The biggest seller for it, for me at least, is that it removes a largely superfluous “return” statement on the getter.

C# properties are all about the syntactic sugar, so why not go the last mile?

6 Responses

Subscribe to comments with RSS.

  1. […] Why doesn’t C# support lambdas for properties? (Nathan Evans) […]

  2. javajoe said, on February 2, 2012 at 2:15 PM

    “The biggest seller for it, for me at least, is that it removes a largely superfluous “return” statement on the getter.”

    true if the lambda is an expression … otherwise you still need a return.

    • Nathan Evans said, on February 2, 2012 at 2:29 PM

      Absolutely. Of course this would only be useful for a one-liner getter.

  3. Paul Batum said, on February 3, 2012 at 4:55 AM

    I think syntax would just be confusing to people learning the language. The symbol before the arrow is an argument identifier in the case of a lambda expression, but in your version its some sort of label. Sure it saves a couple of characters but it doesn’t make a whole lot of sense.

    I think the C# team would be better addressing some of the other problems with properties, such as the inability to specify a readonly auto property.

  4. cmartin said, on February 3, 2012 at 7:00 AM

    read-only auto-property?

    public string Name { get; private set; }

    bam!🙂

  5. […] Why doesn’t C# support lambdas for properties? – Nathan Evans […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: