0

These 4 classes do the same but can someone explain why should you use one instead of theother?

public class MyClass
{
    public string MyString { get; set; }
}

public class MyClass
{
    public string MyString;
}

public class MyClass
{
    private string _mystring;
    public string MyString
    {
      get { return (string)GetValue(_mystring); }
      set { SetValue(_mystring, value); }
    }
}

public class MyClass
{
    private string _mystring;
    public string MyString
    {
        get { return _mystring; }
        set { _mystring = value; }
    }
}

I can interface any of them with

MyClass m=new MyClass();
m.MyString="test";

Is it personal coding preference or is there a reason for each?

Daniel
  • 1,064
  • 2
  • 13
  • 30
  • Check this link, it contains explanations to some of your inquiries. http://msdn.microsoft.com/en-us/library/ms173118.aspx – user2517028 Mar 04 '14 at 00:42
  • 1
    possible duplicate of [What is the difference between a field and a property in C#?](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c) – Selman Genç Mar 04 '14 at 00:42

2 Answers2

0

In my humble opinion, the 1st, 3rd, and 4th are just different ways to declare a property of the class (with the get and set accessor). The 1st way is probably the fastest to declare a property, but with limited flexibility compared to the 3rd and 4th.

The 2nd function uses something different from a property, it has a public field, which is considered a bad practice. We should always use properties to access private members of the class.

Minh
  • 1
  • 1
0

All of your examples are effectively equivalent in practice, though if you implement as property set/get methods, you have the ability to intervene in the process, for example you could notify that a value was changed;

public class MyClass
{
    public event PropertyChangedHandler PropertyChanged;

    private string myString;
    public string MyString
    {
        get
        {
            return myString;
        }
        set 
        {
            // don't allow same value to be set 
            if (value == myString) return;
            myString = value;
            PropertyChanged(this, "MyString");
        }
    } 
}

Other examples might be; add validation logic, add security/authorisation before accepting a set call, return a composite value in a getter.

RJ Lohan
  • 6,497
  • 3
  • 34
  • 54