Setting properties or fields inside a class?

Well, I'm studying properties, and I'm not sure about the following:

class X
{
  private int y;

  public X(int number)
  {
    this.Y=number; // assign to property
    OR
   this.y=number //?
  }

  public int Y;
  {
    get; set;  
  }

}
+3
source share
7 answers

When you use automatic properties ( get; set;or a variant thereof), the background variable is not available. Those, for the most part, can be thought of as simple variables, especially internally.

If you need to execute selective verification or mutation logic in a mutator or otherwise need an explicit backup variable, you cannot use automatic properties, but you have to write stub getand methods yourself set.

+1
source

; Y = number; () y. ( , #) - . :

class X
{
  public X(int y)
  {
    Y = y;
  }
  public int Y { get; set; }    
}

: number y, , this., ( vs ..).

+1

(private int y) , (public int Y {get; set}). , . ... . (DRY).

, , - , , ( ) ... , !

   class X   
   {   
    private int y; //not strictly necessary but good for documentation

    public X(int number)
    {
        Y = number;
    }

    public int Y { get; set; }


    }
+1

autoproperties, :

  public int Y;
  {
    get; set;  
  }

, , :

class X
{   
  public X(int number)
  {
    Y = number;
  }

  public int Y // no semicolon here, comment added for edit length
  {
    get; set;  
  }
}

,

0

:

class X
{
    private int y;

    public int Y
    {
        get { return y; }
        set { y = value; }
    }

    public X(int number)
    {
        Y = number;
        //equivalent to 
        y = number;
        // but you should use the public property setter instead of the private field
    }
}

-, :

class X
{
    private int y;

    public int Y
    {
        get; set;
    }

    public X(int number)
    {
        Y = number;
    }
}
0

, Setter , , . , PropertyChanged.

0

, :

, - , , - .

When changing this value inside (inside the class) it may be a valid time to use a direct backup directly if you intend to skip all the checks and events from the public setter. I like to say, "I'm an instance of a class, I know what I'm doing." In this way, the public setter acts like a guard dog, disinfecting the external entrance, while I can still set the property inside what I need.

class X   
   {   
     private int y; //not strictly necessary but good for documentation

    public X(int number)
    {
        y = GetYValueFromDB();  //we assume the value from DB is already valid

    }

    public int Y { 
       get{ return y}; 
       set { 
       if (ComplexValidation(value)
         {
           RaiseOnYPropertyChanged();
           y = value;
         }
        }


    }
0
source

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


All Articles