0

Possible Duplicate:
Differences between Private Fields and Private Properties

Let's say I have a class MyClass that has a private property MyProp. What's the difference between

public class MyClass
{
  private int MyProp { get; set; }
}

and

public class MyClass
{
  private int MyProp = 0;
}

What's better to use? Thanks.

Community
  • 1
  • 1
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • The first one is a property. The second one is a field. – DOK Jan 10 '12 at 21:12
  • 1
    A repeat of the same type of question... http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – Lloyd Jan 10 '12 at 21:12
  • http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp http://csharpindepth.com/articles/chapter8/propertiesmatter.aspx – Catalin Serafimescu Jan 10 '12 at 21:14

2 Answers2

0

You typically have a combination of a public property and a private field:

public class MyClass
{
    private int _someInt;

    public int SomeInt { get { return _someInt; } set { _someInt = value; } }
}

This always you to create an abstraction layer (the public property) for the class data (the private field). When you create just a property, a private field (I believe) is generated. Is the private field necessary? No. But to explicitly declare it is advisable. That way within the class, the members utilize the private field.