简体   繁体   中英

Difference in declaring public and private variables in a C# class

I have an example as follows:

public static String DocNum
{
    get;
    set;
}

private static String DocNum2;
public static String DocNum2GetSet {
    get
    {
        return DocNum2;
    }
    set
    {
        DocNum2 = value;
    }
}

I was wondering if one declaration benefits the other. Simple question, hoping for a simple answer.

There is no difference in usage; it's just that the first code is neater and therefore easier to write and read. The second code is required if you need to add any extra code, eg validation or raising an event in the setter.

In the second case, you are providing consistent API, where you can later modify the underlying structure without having to have consumers change their code.

For example, right now you are storing DocNum2 in a private string. You could later modify this to go get that data from a file or some other resource and the consumer of the code would be none the wiser.

The first example is referred to as an Auto-Implemented Property . It's shorthand for a full property which is the second of your examples. It's valid in C# 3.0 and later .

It's often sufficient but if you need custom logic or validation the full property is usually what you'll use. You'll also use the full property when doing things that implement INotifyPropertyChanged .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM