ILoggable

A place to keep my thoughts on programming

September 23, 2007 .net , ,

Automatic properties syntax wish

Just a quick thought on on Automatic properties in C# 3.0 (.NET 3.5, Orcas, whathaveyou). I, like most .NET developers, have spent too much time writing

private string foo;

public string Foo
{
 get { return foo; }
 set { foo = value; }
}

This can now be replaced with

public string Foo { get; set; }

Now that’s nice and all, but for the most part it doesn’t seem like a big step up from just making your field public. Now, you do get the benefit of being able to use this property in places where reflection is used for exposing properties, i.e. in most data-binding scenarios, which don’t accept public fields. And it let’s you implement interfaces, since they also can’t define public fields. But that’s a lot more useful, at least to me is replacing

private string foo;

public string Foo { get { return foo; } }

with

public string Foo { get; private set; }

Now you can create those read-only properties with very simple, clean syntax. That’ll clean up a lot of code for me.

But finally we still have the scenario where properties have side-effects, like calling the event trigger for INotifyPropertyChanged. This cannot be expressed with automatic properties and we’re back to defining a separate private field. What I would love to see is some syntactic sugar along the lines of

public string Foo
 : private _foo
{
 get;
 set
 {
   string previous = _foo;
   _foo = value;
   if(previous != _foo)
   {
     OnPropertyChanged("Foo");
   }
 }
}

I know this doesn’t buy that much in syntax terseness (the get is shorter and you don’t have to define the type of _foo), but it means that the private storage used by the property is part of the property definition, which makes the definition that much more easy to read, imho. That, or allow pre and post conditions for set in Automatic Properties, although the syntax i can think of for that doesn’t seem cleaner than the above.

Leave a comment