C# Automatic Properties

前端 未结 11 1128
有刺的猬
有刺的猬 2020-12-05 03:57

I\'m a bit confused on the point of Automatic properties in C# e.g

public string Forename{ get; set; }

I get that you are saving code by no

11条回答
  •  感情败类
    2020-12-05 04:44

    Take a look at the following code and explanation.
    The most common implementation for a property is getter or a setter that simply reads and writes to a private field of the same type as a property. An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates a private backing field.
    Look into the following code:-

        public class Stock 
        {
          decimal currentPrice ;  // private backing field.
          public decimal CurrentPrice 
          {
            get { return currentPrice ; }
            set { currentPrice = value ; }
          }
       }
    

    The same code can be rewritten as :-

       public class Stock
       {
         public decimal CurrentPrice { get ; set ; } // The compiler will auto generate a backing field.
       }
    

    SOURCE:- C# in a Nutshell

提交回复
热议问题