4

Possible Duplicate:
Within the Containing Class, Use Property or Field?

Take a look at the following property:

private string _name;
public string Name 
{  
    get
    {
        return _name;
    }
    set 
    {
        _name = value 
    }
}

Let's say I need access to the name property and I'm in a method within the same class that this property is declared, should I use this.Name or this._name? Is it better practice or at least cleaner to use the Public member?

Community
  • 1
  • 1
user989046
  • 589
  • 2
  • 7
  • 11

2 Answers2

4

You could simplify this code by using auto properties:

public string Name { get; set; }

Now you could use the Name property from within the method.

Backing fields are used when you have some more complex logic in your getter/setter. Then depending on whether you need to access the field or go through the logic in the getter/setter you would use the field or the property.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • But let's say that I have some exception handling in the setter, or let's say another developer comes along at a later stage and adds logic to the getter. This wouldn't be unusual! I'm really probing here to see if it better to always go with the public? – user989046 Jan 27 '13 at 14:56
  • 3
    Then it will depend on whether in your method you need to go through the logic in the getter/setter or not. If you want this logic to be executed you will use the property. If not you will use the field. There's no single rule. It would depend on your exact scenario. – Darin Dimitrov Jan 27 '13 at 14:57
1

I think the best example would be this. In case you use DataBindings properties look often like this:

public string Name
{
    get { return _name; }
    set
    {
        _name = value;
        OnPropertyChanged("Name");
    }
}

So, if you just want to get the name in this class, it doesn't matter if you use it like this.Name or this._name.

On the other hand though, if you'd like to set it, it really depends, if you want to update the UI or not.

My personal convention is, that I use private backingfields, whenever it's possible.

In your case, if there isn't really any more logic in the getter and setter - an auto property would be sufficient.

Michael Schnerring
  • 3,584
  • 4
  • 23
  • 53