Use a private or public property when accessing a property in a method?

Possible duplicate:
Within the class containing the class, use a 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 use the method in the same class that is declared by this property, should this.Name or this._name be used? Is it more efficient practice or at least cleaner to use a public member?

+4
source share
2 answers

You can simplify this code using automatic properties:

 public string Name { get; set; } 

Now you can use the Name property inside the method.

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

+4
source

I think this is the best example. If you use the DataBindings properties, you often look 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, if you want to install it, it really depends if you want to update the interface or not.

My personal agreement is that I use private backingfields whenever possible.

In your case, if there is no more logical logic in the getter and setter, the auto property will suffice.

+1
source

All Articles