C# Automatic Properties - Why Do I Have To Write “get; set;”?

后端 未结 9 1916
失恋的感觉
失恋的感觉 2020-12-29 01:33

If both get and set are compulsory in C# automatic properties, why do I have to bother specifying \"get; set;\" at all?

相关标签:
9条回答
  • 2020-12-29 02:00

    Since no one mentioned it... you could make the auto-property virtual and override it:

    public virtual int Property { get; set; }
    

    If there was no get/set, how would it be overridden? Note that you are allowed to override the getter and not the setter:

    public override int Property { get { return int.MinValue; } }
    
    0 讨论(0)
  • 2020-12-29 02:06

    Because you need some way to distinguish it from plain fields.

    It's also useful to have different access modifiers, e.g.

    public int MyProperty { get; private set; }
    
    0 讨论(0)
  • 2020-12-29 02:10

    Well, obviously you need a way of disambiguating between fields and properties. But are required keywords really necessary? For instance, it's clear that these two declarations are different:

    public int Foo;
    public int Bar { }
    

    That could work. That is, it's a syntax that a compiler could conceivably make sense of.

    But then you get to a situation where an empty block has semantic meaning. That seems precarious.

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