Getters, setters, and properties best practices. Java vs. C#

前端 未结 12 1503
一整个雨季
一整个雨季 2020-12-02 06:32

I\'m taking a C# class right now and I\'m trying to find out the best way of doing things. I come from a Java background and so I\'m only familiar with Java best-practices;

12条回答
  •  日久生厌
    2020-12-02 07:14

    public string Name { get; set; }
    

    This is simply a auto-implemented property, and is technically the same as a normal property. A backing field will be created when compiling.

    All properties are eventually converted to functions, so the actual compiled implementation in the end is the same as you are used to in Java.

    Use auto-implemented properties when you don't have to do specific operations on the backing field. Use a ordinary property otherwise. Use get and set functions when the operation has side effects or is computationally expensive, use properties otherwise.

提交回复
热议问题