.NET 3.5: Property Enhancements

4:31 pm programming

.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.

2 Responses

  1. Laurent Says:

    For info, you can do this:

    public string MyProperty
    {
    get;
    private set;
    }

    This would be a read-only property.

    Laurent

  2. Craig Says:

    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.

Leave a Comment

Your comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.