Properties backing field - What is it good for?

2020-02-10 04:42发布

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?

标签: c#
5条回答
不美不萌又怎样
2楼-- · 2020-02-10 05:02

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.

查看更多
家丑人穷心不美
3楼-- · 2020-02-10 05:03

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

查看更多
4楼-- · 2020-02-10 05:16

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

查看更多
萌系小妹纸
5楼-- · 2020-02-10 05:23

Mostly because you will get a StackOverflow.

查看更多
迷人小祖宗
6楼-- · 2020-02-10 05:23

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

查看更多
登录 后发表回答