When to use get; set; in c#

前端 未结 9 1165
庸人自扰
庸人自扰 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:16

    The syntax you are describing is known as an auto property.

    Before the syntax was introduced in .NET 2.0, we created a property like so:

    int _myVar;
    int MyVar
    {
        get { return _myVar; }
        set { _myVar = value; }
    }
    

    .NET 2.0 introduced the shorthand syntax, allowing the compiler to automatically create the backing variable (_myVar in my example above)

    int MyVar
    {
        get;
        set;
    }
    

    The key difference between setting a variable and a property such as this is that we can control the getting and setting of the property (read only properties, or a function call whenever a value is set to the property, for example.)

提交回复
热议问题