When to use get; set; in c#

前端 未结 9 1167
庸人自扰
庸人自扰 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 basically concept of Object Oriented Programming.

    when you use int i; ( This consider as field and this field can be internal usage as well as it can be use from outside current class depending upon access modifier. (Public , Private , Protected)

    Now when you use get; set; it is property of class. It can also set from other class but diffrence it is access like method and it provide other functionality like notification of property change and all that.

    Use filed when you don't want any control over it but if you want to control then use property. Also you can have get and set with public , private and protected which can also provide more flexibility interm of encaptulation.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-29 21:33

    The part confusing me was the terms accessor, mutator and property, along with the { get; set; }, as though it's some magical improvement alias over just making the field public.

    • accessor = method to access a private field (in C#, both getter/setter)
    • mutator = method to change a private field (just a setter)
    • property = same as an accessor in C#.

    Purely as:

    private int myNumber;
    public int MyNumber { get; set; }
    

    they are totally useless, serving as noise code version for:

    public int myNumber;
    

    If, however you add some checks like so:

    private int myNumber;
    public int MyNumber
    {
        get
        {
            return myNumber;
        }
        set
        {
            if (myNumber < 0)
                throw new ArgumentOutOfRangeException;
            myNumber = value;
        }
    }
    

    ..then they do actually serve the regular used-to getter/setter purpose.

    0 讨论(0)
提交回复
热议问题