Joe Albahari

I'd like to suggest a simple new property declaration syntax for C# 3 that would virtually eliminate property clutter while being highly flexible.

The syntax would consist merely of a type, identifier and then an expression in braces. For example:

int X { _x }

The compiler would translate this to:

int X { get { return _x.Value; } set { _x.Value = value; } }

In order to compile, _x would have to be a type that defines a property/field called Value of matching type (int).

To see how this would be useful, consider a typical property definition:

int _margin;

public int Margin
{
get { return { _margin; } }
set
{
if (_margin == value) return;
int oldValue = _margin;
_margin = value;
OnMarginChanged (oldValue);
}
}

Now suppose we refactor this logic into a generic type:

public delegate void ChangeHandler<T> (T oldValue);

class ChangeProp
{
public event Handler Changed;

public ChangeProp (ChangeHandler changed)
{
Changed = handler;
}

T _value;
public T Value
{
get { return _value; }
set
{
if (object.Equals (_value, value)) return;
T oldValue = _value;
_value = value;
if (Changed != null) Changed (oldValue);
}
}
}

With such a type + the proposed new syntax, we could redeclare our margin field and property as follows:

readonly ChangeProp<int> _margin = new ChangeProp<int> (OnMarginChanged);
public int Margin { _margin; }

This would also make auto-generated code smaller (e.g. SQLMetal).