11

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...");
        }
    }
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Michael Haddad
  • 4,085
  • 7
  • 42
  • 82
  • 4
    `public object Property {get;set;}` – Marian Spanik May 25 '16 at 08:41
  • 5
    Your second example is recursive, you'll get a `StackOverflowException`. – Charles Mager May 25 '16 at 08:41
  • 2
    Second options leads to `StackOverflow` Exception. – Hari Prasad May 25 '16 at 08:42
  • 2
    You don't __need__ a backing field. But the comments in the code suggest that there may be some other logic around the getter and setter. – phuzi May 25 '16 at 08:43
  • 1
    @HariPrasad - i explained why this is not a duplicate... Please reopen the question. – Michael Haddad May 25 '16 at 09:05
  • @Sinatr - How could you say the offered solution is not working if the question doesn't even introduce a problem? There is no solution, just a misunderstanding of a concept. Isn't this site about helping people who have questions about programming? Why being offensive? Is it so hard to be nice? I am here to learn, and there is no such thing as a stupid question. – Michael Haddad May 26 '16 at 11:26
  • @Sipo, my comment was deleted (probably marked as being "rude" or "offensive"), the point is that: you have problem and instead of simply trying what you "thought" you come directly to SO and ask. For me this is a kind of disrespect (laziness). This kind of questions (where the answer is "have you tried it to see it's wrong") is same bad as questions where the answer is "have you tried anything" (where lazy people simply ask for things). I could write an answer where I suggest you to create project in VS and try it, but I think it's enough to simply comment on this matter. – Sinatr May 30 '16 at 07:34
  • @Sinatr - I tried it, and I know it doesn't work, I only asked why. – Michael Haddad May 30 '16 at 07:49

4 Answers4

19

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;
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    @fubo: Thank you for a reasonable question. if property *stores* some value we need a backing field. I've edited the answer. – Dmitry Bychenko May 25 '16 at 09:02
  • 1
    @fubo -Dmitry understood my question and answered it very well. This is not a question about auto-implemented properties. Please reopen the question. – Michael Haddad May 25 '16 at 09:14
  • It is also important when calling an external API such as reading / writing to the Windows Registry, or to some database. In some cases, this may be desired, but in other cases, it may be preferable at certain points in the execution of your logic to store the value in a local variable to avoid excessive I/O operations. – Chiramisu Aug 29 '22 at 21:05
4

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.

odyss-jii
  • 2,619
  • 15
  • 21
  • 2
    That doesn't answer the question about the purpose of the `backing field`. – fubo May 25 '16 at 08:44
  • @fubo yes, it does. The backing field is the actual data container. Property is just syntactic sugar for getter and setter methods. Property contains no data. – odyss-jii May 25 '16 at 08:45
  • 1
    it could also be used to modidy a result `public string Property { get {return backingfield.Trim(); } }` - in that case auto-properties don't work and you need your `_backingField` – fubo May 25 '16 at 08:46
  • @fubo: and this contradicts my point how exactly? As I wrote, property is just a pair of methods. OP seems to think that property contains data, which is why he attempted to return `Property` from getter of `Property`. – odyss-jii May 25 '16 at 08:48
1

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;
    }
Jordan Kniest
  • 200
  • 1
  • 6
1
public object Property
{
    get
    {
        return Property;
    }
    set
    {
        Property = value;
    }
}

This will return the property itself and end up in a recursive loop, a stack overflow. Therefore you want to return another object, for example _property.

Carra
  • 17,808
  • 7
  • 62
  • 75