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

前端 未结 12 1508
一整个雨季
一整个雨季 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:23

    First let me try to explain what you wrote:

    // private member -- not a property
    private string name;
    
    /// public method -- not a property
    public void setName(string name) {
       this.name = name;
    }
    
    /// public method -- not a property
    public string getName() {
       return this.name;
    }
    
    // yes it is property structure before .Net 3.0
    private string name;
    public string Name {
       get { return name; }
       set { name = value; }
    }
    

    This structure is also used nowadays but it is most suitable if you want to do some extra functionality, for instance when a value is set you can it to parse to capitalize it and save it in private member for alter internal use.

    With .net framework 3.0

    // this style is introduced, which is more common, and suppose to be best
    public string Name { get; set; }
    
    //You can more customize it
    public string Name
    {
        get;
        private set;    // means value could be set internally, and accessed through out
    }
    

    Wish you better luck in C#

提交回复
热议问题