Tutorial :Properties backing field - What is it good for?



Question:

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?


Solution:1

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


Solution:2

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


Solution:3

Mostly because you will get a StackOverflow.


Solution:4

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


Solution:5

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »