C # getters, setters declaration

Possible duplicates:
Why use getters and setters?
C # 3.0 Auto-Properties - useful or not?

Is there a difference between the defining properties as follows:

// private, with getter & setter private string fName; public string Name { get { return this.fName } set { this.fName = value } } // define as a Property public string Name { get; set;} 

As far as I can tell, this only seems to be a stylistic preference. Did I miss something?

+15
syntax c # getter getter-setter
Feb 07 '11 at 16:22
source share
5 answers

Differences:

  • The second form will only be compiled using the C # 3 compiler or later
  • The second form does not allow any code (even in the same class) to directly access the field, since the real field has an "inexpressible name"

The second version is what is known as an automatically implemented property (or “automatic property” for short). They were introduced in C # 3. If you are only writing code that looks like the first version, that is, there is no logic, then the automatic properties are great. You can always add logic later by translating it into the first form. All of your code will be compatible with this change in both the source and binary compatibility conditions.

Remember that automatic properties do not allow you to specify default values, and there is no such thing as a truly automatic readonly property (i.e. one without a getter). The closest you can become a public recipient with a private setter, for example.

 public string Name { get; private set; } 

This is not quite the same, but it is close enough in many situations.

+26
Feb 07 '11 at 16:23
source share

The first is a standard property. You must define a field to store the value. The second is an automatically implemented property , available only in C # 3.0 and later.

+2
Feb 07 '11 at 16:24
source share

The answer is in IL. Use ildasm and compare.

http://msdn.microsoft.com/en-us/library/f7dy01k1%28v=VS.90%29.aspx

0
Feb 07 '11 at 16:23
source share

Ultimately, in this case, it works with the same thing. The difference arises when you want to apply some rules to get / setting, in which case you need to use the private / protected variable and hide it behind the public property.

0
Feb 07 '11 at 16:24
source share

No. In fact, when you use the shorter version ( public string Name { get; set; } ), the compiler automatically creates a private field for this property.

0
Feb 07 '11 at 16:25
source share



All Articles