2

Possible Duplicate:
What is the difference between a field and a property in C#?
Difference between Property and Field in C# .NET 3.5+

I have seen that in c# the following pattern is common:

   private string m_name = string.Empty;

public string Name
{
    get
    {
        return m_name;
    }
    set
    {
        m_name = value;
    }
}

why do we use a field and a property to hold a value when we can use a simple variable? why should I use fields and properties instead of a simple variable?

Community
  • 1
  • 1
mmilan
  • 1,738
  • 8
  • 31
  • 57
  • See the wide range of answers in the above question – Kieren Johnstone Dec 05 '12 at 18:55
  • It depends on what you want to pre-process the value. Imagine if you (for some reason) wanted to make sure any string saved as Name contained at least 1 'e', you could do all the logic in the setter instead of in the main code body. – Ichabod Clay Dec 05 '12 at 18:56

3 Answers3

2

Just for encapsulation principle. For hinding concrete implementaiton, and plus, you have an opportunity (in this case) to add additional code inside get/set.

If you don't need addittional code, you can use just

public string Name{get;set;}

or use fileds, as you would like. But using properties is a guideline offered by Microsoft.

So basically all, follow it.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

There are a lot of reasons for this, but 2 come to mind right away:

First, a property can be easily bound to a control or other reflection-based controls that read all properties (rather than fields).

Second, there may be actions that you want to perform in getters or setters (such as firing a NotifyPropertyChanged event).

Steve Danner
  • 21,818
  • 7
  • 41
  • 51
0

Properties provide the opportunity to protect a field in a class by reading and writing to it through the property. In other languages, this is often accomplished by programs implementing specialized getter and setter methods. C# properties enable this type of protection while also letting you access the property just like it was a field.

Another benefit of properties over fields is that you can change their internal implementation over time. With a public field, the underlying data type must always be the same because calling code depends on the field being the same. However, with a property, you can change the implementation.

evilone
  • 22,410
  • 7
  • 80
  • 107