开发者

Difference between empty property declaration [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C# getters, setters declaration

What's the difference between these property declarations ? How do they work and why is one preferred.

public string aString {get;set;}

OR

    private string bString = "";
    public string aString
    {
        get { return bString; }
        set { bString = value; }
    }

NOTE : THis is not a urgent or importa开发者_JAVA百科nt question , rather a matter of asking the people who know why something should be done a certain way. Also, please give examples of which scenario is best for each implementation.


First is automatic property and the second is classic property that we have known.

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.

When you don't have any special logic to add in the get and set part property then you can just use automatic property since its less code and less code means easier maintenance and less bugs.

You should switch to classic property syntax only if you need to add some logic (like validation) on the property.


Design: Use second if you need to do something in exact moment of assignment (raise an event , change other fields, save undoredo information, write to a file and tons of other possibilities).

Practical: Use second if you need simply to debug, as you can not put a breakpoint on autogenerated property.

Use first in all other cases.


The most obvious difference is that you can't set the aString variable and return it, since you always return bString...


One difference is that in the case of automatic property you can't have a private setter. This is just a language shortcut or syntax sugar to make things easier to develop (also generated code looks cleaner...). If you look at the compiled assembly the compiler made exact the same code as in the "classic" variation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜