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

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

    If all you need is a variable to store some data:

    public string Name { get; set; }
    

    Want to make it appear read-only?

    public string Name { get; private set; }
    

    Or even better...

    private readonly string _name;
    
    ...
    
    public string Name { get { return _name; } }
    

    Want to do some value checking before assigning the property?

    public string Name 
    {
       get { return m_name; }
       set
       {
          if (value == null)
             throw new ArgumentNullException("value");
    
          m_name = value;
       }
    }
    

    In general, the GetXyz() and SetXyz() are only used in certain cases, and you just have to use your gut on when it feels right. In general, I would say that I expect most get/set properties to not contain a lot of logic and have very few, if any, unexpected side effects. If reading a property value requires invoking a service or getting input from a user in order to build the object that I'm requesting, then I would wrap it into a method, and call it something like BuildXyz(), rather than GetXyz().

提交回复
热议问题