galbarm
galbarm

Reputation: 2543

Properties backing field - What is it good for?

On one hand, I know that the advisable usage of Properties is to have a backing field, like in the following example:

    private int m_Capacity;

    public int Capacity
    {
        get { return m_Capacity > 0 ? m_Capacity : -666; }
        set { m_Capacity = value; }
    }

On the other hand, what benefit do I get from using the above example over discarding the field and using only the property for all purposes, like in the following example:

    public int Capacity
    {
        get { return Capacity > 0 ? Capacity : -666; }
        set { Capacity = value; }
    }

What is good about using a backing field for regular (non-auto-implemented) properties?

Upvotes: 15

Views: 38281

Answers (5)

Gerard Simpson
Gerard Simpson

Reputation: 2126

Backing fields support the concept of encapsulation.

Encapsulation allows you to later change the implementation details of the class without changing its interface.

This means that having a backing field with getters and setters instead of having a public class member will make your code more robust and/or readable for future developers or your future self.

Upvotes: 5

sourcenouveau
sourcenouveau

Reputation: 30524

Don't forget that Properties are simply shorthand syntax for generating getter and setter methods. They look like fields, but they are not.

Upvotes: 7

Ray
Ray

Reputation: 21905

The explicit private memberid is useful if you ever need to access the actual value of m_Capacity, rather than the 'managed' value you get from the Capacity property,

EDIT: The other posts correctly point out the syntax error. I should have mentioned it too, but I ignored it and just tried to answer his question, which seemed to be about automatic properties

Upvotes: 11

marcind
marcind

Reputation: 53183

If you do this:

public int Capacity 
{ 
    get { return Capacity > 0 ? Capacity : -666; } 
    set { Capacity = value; } 
}

then your code will have an infinite recursion. It will never work. That's because the getter for Capacity is referencing itself. Same thing goes for the setter.

Unless you are using automatic properties, you need a backing field

Upvotes: 33

btlog
btlog

Reputation: 4780

Mostly because you will get a StackOverflow.

Upvotes: 3

Related Questions