Matt
Matt

Reputation: 2379

Auto-property vs. protected variable with public accessors

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?

Upvotes: 0

Views: 384

Answers (2)

Douglas
Douglas

Reputation: 54877

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.

Upvotes: 2

Tigran
Tigran

Reputation: 62248

This can be advantage, don't know if it's in your domain so, if you think that the class that derives from that class can access the field MyEnumerationType _foo, avoiding in this way (for some reason) access it via property.

It's hard to say if in your specific context there is some meaning, but, I repeat, there could be meaning described above.

For example, if I would have :

public MyEnumerationType Foo
{
    get { return _foo; }
    set { 
           this._foo = (MyEnumerationType) value; 
           TriggerSomething(..);
       }
}

so setting that property I would trigger some actions in my environment, accessing the field directly will help me avoid unnecessary (for architectual decisions) triggering, if I change that field from some child class.

Upvotes: 1

Related Questions