What are the benefits of using properties internally?

后端 未结 5 705
猫巷女王i
猫巷女王i 2020-12-10 19:19

Encapsulation is obviously helpful and essential when accessing members from outside the class, but when referring to class variables internally, is it better to call their

相关标签:
5条回答
  • 2020-12-10 19:22

    There shouldn't be a significant performance difference, and the reason you stick to using the properties is because that's the whole point of encapsulation. It keeps all accesses of those private members consistent and controlled. So if you want to change the property getter/setter you don't have to think "do I need to duplicate the same functionality elsewhere in the places where I decided to access the private member directly?"

    0 讨论(0)
  • 2020-12-10 19:22

    The performance difference is neglectable, in about 98% of the time.

    You should always use properties even though your getter or setter just get or set your private member. This will allow you to bring changes as your application evolves. Doing so, you'll be able to bring some restrictions or some other encapsulation within your properties without breaking your code. Otherwise, once you decide to write properties because of a reason X, you'll find yourself obliged to refactor all of your code to get or set the property instead of your private member.

    0 讨论(0)
  • 2020-12-10 19:26

    I like to use internal properties for lazy initialization, where in the property you make sure the object is initialized. This ensures I am not using class level variables that have not yet been initialized.

    TestClass1 _class1
    internal TestClass1
    {
    
    get
    {
    
        if (_class == null)
         _class = new TestClass1()
    
        return _class1
    
    }
    
    }
    
    0 讨论(0)
  • 2020-12-10 19:43

    The benefit would be in the cases where there was validation to be done on the Get or Set. This would be in one place and always called.

    As far as I know (from other questions asked on Stack Overflow) when the Getter simply returns the value the code generated is the same as for accessing the variable directly.

    0 讨论(0)
  • 2020-12-10 19:49

    Accessing the field directly or using the getter usually doesn't make a big difference, unless your getter performs some lazy initialization or other processing. So it depends on what the getter does, but my rule of thumb is to always use the getter except in specific cases.

    To assign a value to the field, don't forget that setters often include validation code or raise an event. In that case you should always use the setter.

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