views:

132

answers:

5

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

+2  A: 

they are both correct.. the second is the deprecated form

Not deprecated, just a bit pointless in many cases (unless you like the extra typing).
LukeH
-1: it's not deprecated.
John Saunders
+8  A: 

The shorthand syntax (auto implemented properties) in your first example was introduced in C# 3.0, and was not valid before then. The compiler actually converts them to the full form with backing fields.

Before C# 3.0, the only correct way to define properties was with backing fields.

Even with C# 3.0, if you want to have any logic in your properties, you need to convert them to use backing fields.

In short - for dumb properties (those that do nothing), use auto properties. They make your code simpler and easier to read and can be converted.

Oded
Thanks for mentioning the potential step of converting the automatic properties. I'd like to also add that publishing these values as automatic properties means that you can change them to manually-backed properties later without breaking the interface at the binary level. In contrast, public fields (ick!) are not binary compatible with public properties of the same name.
Steven Sudit
+10  A: 

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.

KP
+1; the first is a whole lot more convenient for dumb properties, and can easily be converted into the second if you find yourself needing logic.
tzaman
@tzaman: well said. My thoughts exactly.
KP
+3  A: 

The two classes you have are in practice identical in functionality and features.

The purpose of the automatic properties syntax (the first class) is to basically give you a quick way to declare what is essentially the same as the second class you show.

I would stick with the first version until you need to add code to the getter or setter method (like validating a new value for the property.)

The purpose of the automatic property syntax is dual, it was partly added to facilitate Linq, and partly added to make it easier to just ensure you declare properties, and not public fields.

If you declare a class using automatic properties (again, the first version), then all other assemblies compiled against your code will know that your class declares these things as properties, and not as fields. If you later decide that you need to add code, like validation, those other assemblies does not have to be recompiled, since they still find the properties.

Lasse V. Karlsen
Could you elaborate on how automatic properties facilitate LINQ? I don't see the connection myself.
LukeH
They were added as part of the anonymous types package.
Lasse V. Karlsen
Ok, I still don't see why they were needed for Linq. Hm...
0xA3
I don't either to be honest :) All I know is that they were added to make the compiler able to easier handle anonymous types.
Lasse V. Karlsen
A: 

You could also use Access Modifier for get and set...

public {ReturnType} MyProperty { {Access Modifier}get; {Access Modifier}set; }

And I assume that you already have knowledge of Access Modifier.

Samdrain