Sipo Sipo - 3 months ago 9
C# Question

Do we need backing fields in C# properties?

NOTE: This is not a question about auto-implemented properties. Auto-implemented properties are about properties without logic in the getters and setters while I stated in my code very clearly that there is some logic. This is not a duplicate since the question is really different, and so is the answer. However, I will insert some specific logic to the code so it will be clearer.




I see a lot of this:

private int _age;
public object Age
{
get
{
if(user.IsAuthorized)
{
return _age;
}
}
set
{
if(value > 0 && value < 120)
{
_backingField = value;
}
else
{
Console.Write("Non-valid age");
}
}
}


But why do we need the backing field? Why no returning the Property itself as shown below?

public object Age
{
get
{
if(user.IsAuthorized)
{
return Age;
}
}
set
{
if(value > 0 && value < 120)
{
Age = value;
}
else
{
Console.Write("Non-valid age");
}
}
}

Answer

Well, returning property itself leads to Stack Overflow exception:

public object Property 
{
    get
    {
        return Property;
    }
    set
    {
        Property = value;
    }
}

Imagine

  MyObject o = new MyObject();

  // cause Stack Overflow exception
  o.Property = null;

It easy to see why:

  1. setting Property = null calls set
  2. which call Property = value; which in turn calls set
  3. which call Property = value;... and so on.

So if property stores some value the value should be stored in a field (you need a field), we can't use a property to store itself. If you want to shorten the code, put it like this (auto properties):

  public object Property { 
    get; // let .Net create a backing field for you
    set;
  }