How to properly define class properties?

rlcrews picture rlcrews · Jul 9, 2010 · Viewed 15.1k times · Source

When defining a new class within a project what is the correct/best practice for doing so? In the past I have created classes such as:

  public class MyClass
  {
      public string FirstName  {get; set;}
      public string LastName  {get; set;}
  }

Normally I’d use a class such as this for the creation of collections within a project.

However as I continue to learn and read more about c# sharp I see examples where classes are defined as:

    class MyClass //not set to public
    {
        private string  _firstName; //first defined as fields
        private string _lastName;

        public string FirstName  // then defined as properties 
        {
            get { return  _firstName; }
            set { _firstName = value; }
        }
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value; }
        }
    }

Is the first approach incorrect in definition or is this an accepted shorthand version within C#? As a best practice should you always first define the class with private fields and then define them as properties using get / set to a value?

I ask because I am self taught in C# and I am trying to improve and well as better understand the proper approach to development and some samples and tutorials out there simply state approaches without a solid explanation as to why one approach is preferred (or should be done) over the other.

Thanks in advance

Answer

KP. picture KP. · Jul 9, 2010

Your first example of:

public class MyClass
{
    public string FirstName  {get;  set;}
    public string LastName  {get;  set;}
}

is specifically Auto-Implemented Properties, introduced in c# 3.0. Neither format is wrong. The first is more of a 'shorthand'.

With more complex types, it is sometimes still useful to use the old style, and expose only certain properties or values from a private variable, such as:

public class MyClass
{
    private Dictionary<int, List<string>> _someInternalDictionary;

    public int MyValuesCount
    {
        get
        {
            return _someInternalDictionary.Values.Count;
        }
    }

}

A crude example but hopefully you get my idea.