Using a value from a private variable or from an actual property in class functions?

When referring to class properties from a function inside a class, do you use the value from the actual property or the value of a private variable?

Which way is better? Why?

public class

  private m_Foo as double

  public property Foo() as double
    get
      return m_Foo
    end get
    set(byval value as double)
      m_Foo = value
    end set
  end property

  public function bar() as double
    Dim x as double = 5 * m_Foo
    Dim y as double = 3 * Foo
  end function

end class
+1
source share
6 answers

Personally, I try to use get / set accessor when possible, so as not to be surprised when I change my logic, and suddenly the places where I access the private field do not work properly.

+7
source

- - , . .

+3

. , . , . , - , .

+1

, ( ) , get. , get -, "" , , .

+1

, .

public class MyClass 
{

   private List<string> _someList;

   public List<string> SomeString
   {
      get
      {
         if(_someList == null)
            _someList = new List<string>();
         return _someList;
      }
   }

}

_someList, . .

Some may argue that a private variable should simply be declared as new in the first place or initialized in the constructor, and not as a property, but this should at least highlight a possible problem, since this is a general approach.

0
source

Source: https://habr.com/ru/post/1748585/


All Articles