5

Possible Duplicate:
What is the difference between a field and a property in C#

Can someone explain the diffrence if any between these two properties?

 public string City { get; set; }
 public string City;
Community
  • 1
  • 1
Tom Squires
  • 8,536
  • 10
  • 45
  • 71

3 Answers3

7

The first one is an actual property. The second one is just a field.

Generally speaking, fields should be kept private and are what store actual data. Properties don't actually store any data, but they point to fields. In the case of the auto-property above, it will auto-generate a hidden field like _city behind the scenes to hold the data.

Hope this helps!

mellamokb
  • 55,194
  • 12
  • 105
  • 134
1

First one is CLR property, while the second is just public field (not a property).

In WPF and Silverlight, binding doesn't work with public fields, it works only with public properties. That is one major difference in my opinion:

 //<!--Assume Field is a public field, and Property is a public property-->
 <TextBlock Text="{Binding Field}"/>
 <TextBlock Text="{Binding Property}"/>

First one wouldn't work but the second one would work.

Nawaz
  • 341,464
  • 111
  • 648
  • 831
0

as mellamokb said. the first type is Property,the compiler will auto-generate access function and private field like:

private String _city;
public String City(){  return  _city ;}
.....

use Properties,you can control the access of _city,for example"

public String City(){  
doXxxFunction();
return  _city ;
}

so,you should always use the property,and make sure all field is private.

deskmore
  • 488
  • 4
  • 3