C# – Private Variable vs Property

cprogramming practices

When setting a value to a variable inside of a class most of the time we are presented with two options:

private string myValue;
public string MyValue
{
   get { return myValue; }
   set { myValue = value; }
}

Is there a convention that determines how we should assign values to variables inside of our classes? For example if I have a method inside the same class should I assign it using the property or using the private variable. I've seen it done both ways, so I was wondering if this is a choice or performance is a factor (minor, probably).

Best Answer

I would take it a step further, and bring it to 3 cases. Although there are variations on each, this is the rules I use the majority of the time when C# programming.

In case 2&3, always go to the Property Accessor (not the field variable). And in case 1, you are saved from even having to make this choice.

1.) Immutable property (passed in to constructor, or created at construction time). In this case, I use a field variable, with a read-only property. I choose this over a private setter, since a private setter does not guarantee immutability.

public class Abc
{ 
  private readonly int foo;

  public Abc(int fooToUse){
    foo = fooToUse;
  }

  public int Foo { get{ return foo; } }
}

2.) POCO variable. A simple variable that can get/set at any public/private scope. In this case I would just use an automatic property.

public class Abc
{ 
  public int Foo {get; set;}
}

3.) ViewModel binding properties. For classes that support INotifyPropertyChanged, I think you need a private, backing field variable.

public class Abc : INotifyPropertyChanged
{
  private int foo;

  public int Foo
  {
    get { return foo; }
    set { foo = value;  OnPropertyChanged("foo"); }
  }
}
Related Topic