properties in C#

前端 未结 4 1315
慢半拍i
慢半拍i 2020-12-31 05:00

Why are we able to write

public int RetInt
{
   get;set;
}

instead of

public int RetInt
{
   get{return someInt;}set{someI         


        
4条回答
  •  攒了一身酷
    2020-12-31 05:17

    This feature is called Auto implemented properties and introduced with C# 3.0

    In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

    class Customer
    {
        // Auto-Impl Properties for trivial get and set 
        public double TotalPurchases { get; set; }
        public string Name { get; set; }
        public int CustomerID { get; set; }
    

    For your question

    What is the difference between the two?

    In your case, none. Since you are not doing anything while setting or retrieving the value, but suppose you have want to do some validation or want to perform other types of check then :

    private int someInt;
    public int RetInt
    {
        get
        {
            if (someInt > 0)
                return someInt;
            else
                return -1;
        }
        set { someInt = value; } // same kind of check /validation can be done here
    }
    

    The above can't be done with Auto implemented properties.

    One other thing where you can see the difference is when initializing a custom class type property.

    If you have list of MyClass Then in case of Normal property, its backing field can be initialized/instantiated other than the constructor.

    private List list = new List();
    public List List
    {
        get { return list; }
        set { list = value; }
    }
    

    In case of Auto implemented property,

    public List SomeOtherList { get; set; }
    

    You can only initialize SomeOtherList in constructor, you can't do that at Field level.

提交回复
热议问题