1

When I declare a variable in a class like this:

public class Test
{
    public string x = 0;
}

and another like this:

public class Test2
{
    public string x {get; set;}
}

What is the difference?

h313
  • 148
  • 2
  • 7
  • 2
    First one is a public field. Second one is a public auto-implemented property. Google for difference – Sergey Berezovskiy Dec 12 '13 at 00:27
  • Can you explain that? I'm relatively new to OOP, as I started with BASIC. – h313 Dec 12 '13 at 00:28
  • 3
    @H313 Now, when you know they are called **field** and **property** you can find a lot of good and already answered questions about differences between these two, like this one: [What is the difference between a field and a property in C#?](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c) – MarcinJuraszek Dec 12 '13 at 00:28

1 Answers1

1

Usually neither called "variable". First one is "field", second one is "property" (auto-implemented property).

Excerpt from MSDN on "field":

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.

Excerpt from MSDN on "property":

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159
  • So, what would the difference be in here? – h313 Dec 12 '13 at 00:28
  • 1
    The difference is that a property is only accessed through get and set methods, which can be extended to invoke some Changed event or do some kind of validation, and the code compiled against them will not break, as long as they don't now throw exceptions or something. Changing a field to a property is a breaking change. – Magus Dec 12 '13 at 00:33
  • I see the emphasis being on *control*, with a property, the class can exercise control over what other objects can see or do with the value or reference. – Will Faithfull Dec 12 '13 at 00:52