0

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.

1
  • I believe the first is shorthand only available in .NET 4.0 or newer. Commented Mar 18, 2014 at 23:15

3 Answers 3

3

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, e.g. validation or raising an event in the setter.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.