Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need backing fields in C# properties?

Tags:

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 of this question nither, since the question is really different, and so is the answer.


I see a lot of this:

private int _age;
public int Age
{
    get
    {
        if(user.IsAuthorized)
        {
            return _age;
        }
    }
    set
    {
        if(value >= 0 && value <= 120)
        {
            _age = value;
        }
        else
        {
            throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
        }
    }
}

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

public object Age
{
    get
    {
        if(user.IsAuthorized)
        {
            return Age;
        }
    }
    set
    {
        if(value >= 0 && value <= 120)
        {
            Age = value;
        }
        else
        {
            throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
        }
    }
}
like image 365
Michael Haddad Avatar asked May 25 '16 08:05

Michael Haddad


3 Answers

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;
  }
like image 106
Dmitry Bychenko Avatar answered Oct 11 '22 00:10

Dmitry Bychenko


The property there is actually just two hidden methods: get_Property and set_Property. If you return Property from the getter of Property you are in fact causing an infinite recursive loop which will lead to a stack overflow exception: you are calling the method get_Property from the method get_Property, which in turn calls get_Property and so forth.

EDIT: As clarified in the comments, the property is only the two methods and nothing more. There is nothing to hold data; the backing field is what actually contains the data. If you want to store Age as data in the instance, something must hold that data which is why you need the backing field.

Auto-properties automatically create the backing field:

public object Property { get; set; }

In all other cases, the property is just two methods and all data storage is separate and you must handle it yourself.

like image 41
odyss-jii Avatar answered Oct 11 '22 02:10

odyss-jii


Everytime you set a value to Property, the set-block will be called. So in your example it would be like:

Property = 10
-- Inside set: Property = Set
----- Called again set: Property = Set
----------- And so on and so o

n

But, you can do the following:

    public int Property
    {
        get;
        set;
    }
like image 34
Jordan Kniest Avatar answered Oct 11 '22 01:10

Jordan Kniest