In some code that I’ve recently inherited the responsibility for, I’ve found several instances where the original developer did something like the following:
protected MyEnumerationType _foo;
public MyEnumerationType Foo
{
get { return _foo; }
set { this._foo = (MyEnumerationType) value; }
}
This seems unnecessarily verbose to me and I’m curious as to whether there is some advantage to doing this instead of simply using an auto-property:
public MyEnumerationType Foo { get; set; }
Am I missing something? Is there some advantage to the first section of code above that I’m not aware of?
The likelihood is that the original code was written before C# 3.0 was released, which is when auto-implemented properties were introduced. In earlier versions of the language, the first approach is the only one that was possible.
In C# 3.0 and later, the main advantage to explicitly defining the backing field is to perform operations on it that are not possible through properties, such as initializing it with a default value (which would otherwise have to be done through a constructor) and declaring it as volatile.