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; 
0

3 Answers 3

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!

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

Comments

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.

Comments

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.

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.