Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties backing field - What is it good for?

Tags:

c#

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?

like image 785
galbarm Avatar asked Jul 17 '10 19:07

galbarm


People also ask

What is the use of backing field?

A Backing Field is just a field that will be generated for a property in a class only if it uses the default implementation of at least one of the accessors. Backing field is generated only if a property uses the default implementation of getter/setter. If you see the following code with perspective of Java.

What is a backing property?

The backing fields feature allows us to access a field of a property only in a scope of getter and setter.

Why are properties better than fields?

Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property.

What is Kotlin backing field is used for?

As shown above, when a property needs its backing field, Kotlin provides it automatically. Moreover, we can reference the backing field inside custom accessors via the field identifier. Put simply, the backing field is where the value for a property will be stored.


1 Answers

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

like image 97
marcind Avatar answered Oct 17 '22 11:10

marcind