1

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

what's the different between this:

class Name {
  public int x;
}

and this:

class Name {
  int cx;
  public int x {
    get { return cx; }
    set { cx = value; }
  }
}

is it the same thing or are there some differences? Thank you

Community
  • 1
  • 1
Frank Lioty
  • 949
  • 3
  • 10
  • 17

1 Answers1

4

They are different.

In the first x is a Field, in the latter x is a Property. While Properties are "accessed just like Fields" in code, this is just the beauty of C#; the different definitions actually result in different incompatible types1.

Using auto-properties would be equivalent to the latter (but is much easier to write):

class Name {
    public int x { get; set; }
}

I like this answer by Brian Rasmussen, to a related/duplicated question:

Fields and properties look the same, but they are not [the same]. Properties are methods and as such there are certain things that are not supported for properties, and some things that may happen with properties but never in the case of fields.

The answer then goes on to list some key differences covering usage and observable semantics.


1 Changing a Field to a Property (or vice-versa) is a type-breaking change and requires that early-bound (e.g. statically-typed) code is recompiled against the new type.

Community
  • 1
  • 1