Auto-properties with or without backing field - preference?

前端 未结 1 1212
孤街浪徒
孤街浪徒 2020-12-16 01:44

I know that when using auto-properties, the compiler creates its own backing field behind the screen. However, in many programs I read to learn from, I see people explicitly

相关标签:
1条回答
  • 2020-12-16 02:07

    There's not much difference between those two snippets - you can't pass a property by reference, for example, but that's rarely an issue. However, if you want the field to be readonly, like this:

    private readonly int _backingField;    
    public int Property { get { return _backingField; } }
    

    then there's a difference. The code I've written above prevents the value from being changed elsewhere within the class, making it clear that this is really meant to be immutable. I'd really like to be able to declare a read-only field with a read-only automatically implement property, settable only within the constructor - but that's not available at the moment.

    This is rather confusing, by the way:

    Also, I understand that you have to explicitly use the backing field in the case of structs, you can't access their members via properties.

    What do you mean? You can definitely use properties within structs. Are you talking about backing fields which are mutable structs, i.e. the difference between:

    foo.someField.X = 10;
    

    and

    foo.SomeProperty.X = 10;
    

    ? If so, I normally avoid that being an issue by making my structs immutable to start with :)

    0 讨论(0)
提交回复
热议问题