Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public accessors vs public properties of a class [duplicate]

Tags:

c#

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;
like image 988
Tom Squires Avatar asked Sep 22 '11 15:09

Tom Squires


2 Answers

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!

like image 163
mellamokb Avatar answered Nov 14 '22 22:11

mellamokb


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.

like image 29
Nawaz Avatar answered Nov 14 '22 22:11

Nawaz