.NET 3.5: Property Enhancements

November 20, 2007 by Craig

.NET 3.5 adds a few syntax enhancements regarding properties.

Automatic Properties

You no longer have to declare the private field, getter, or setter methods when creating a property; the compiler will handle it for you.

class Foo {
  public String Bar { get; set; }
}

When I first started learning .NET, I actually thought that this feature had already been built into the language, and was surprised when I found I had to write my own (repetitive) property code. Automatic properties finally alleviates that.

Note: You can only declare read-write automatic properties. If you want a read-only or a write-only property, you have to do the legwork yourself. Note that access modifiers can still be used, so you could have a public property with a private setter — but that’s not the same thing as read-only.

Property Initialization

There’s a new syntax for assigning values to properties during object creation:

Foo foo = new Foo { Bar = "bar", Baz = 1 };

If you have mutable objects that don’t have any constructor logic, then this enhancement helps reduce a lot of verbose dereferencing code with a nice constructor-like syntax. Generally I prefer my classes immutable and constructor-populated, but there’s lots of times where that’s not feasible.

This makes two worthwhile enhancements to properties. Unfortunately, by themselves they wouldn’t do me much good: I intentionally avoid using properties (in favor of explicit getter/setter methods) because properties are completely unusable with delegates. However, some of the other new .NET features help to compensate for this, so I’m still counting these features as a win.


3 Comments »

  1. For info, you can do this:

    public string MyProperty
    {
    get;
    private set;
    }

    This would be a read-only property.

    Laurent

    Comment by Laurent — May 25, 2008 @ 3:28 am

  2. I alluded to this in my post. The property you created is only externally read-only. The code inside the class itself can write to the property as much as often as it wants. This is not the same effect as marking a field “readonly”.

    See my recent post for some more discussion about how the “readonly” modifier works and what I expect from it.

    Comment by Craig — May 25, 2008 @ 7:32 am

  3. Yes, I just saw this feature. Working on a new app I ripped out all the repetitive private module variables. Great post!

    Comment by Patrick — April 17, 2009 @ 5:29 am

RSS feed for comments on this post. TrackBack URL

Leave a comment