When to use get; set; in c#

前端 未结 9 1217
庸人自扰
庸人自扰 2020-12-29 20:59

I\'m failing to understand what the difference is between initializing a variable, getting its value like this:

 //define a local variable.
   int i;

   i=          


        
9条回答
  •  太阳男子
    2020-12-29 21:31

    It is one concept of OOPs.

    There are two main advantages using the Get\Set Property :

    1. Without affecting base class value, we can change the variable value in derived class using the get and set method.

    Eg :

    class User
    {
    
        private string name = "Suresh Dasari";
        public string Name
        {
         get
            {
                return name.ToUpper();
    
            }
    
            set
            {
           if (value == "Suresh")
                 name = value;
           }
            }
        }
    
    1. Also, we can able to validate\Restriction\Raise the Events, in values set property section.

提交回复
热议问题