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

前端 未结 12 1509
一整个雨季
一整个雨季 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条回答
  •  旧时难觅i
    2020-12-02 07:13

    like most of the answers here, use Automatic properties. Intuitive, less lines of code and it is more clean. If you should serialize your class, mark the class [Serializable]/ with [DataConract] attribute. And if you are using [DataContract] mark the member with

    [DataMember(Name="aMoreFriendlyName")]
    public string Name { get; set; }
    

    Private or public setter depends on your preference.

    Also note that automatic properties require both getters and setters(public or private).

    /*this is invalid*/
    public string Name 
    { 
        get; 
       /* setter omitted to prove the point*/
    }
    

    Alternatively, if you only want get/set, create a backing field yourself

提交回复
热议问题