Automatic Properties

Classic Object Oriented Programming (OOP) uses a Class model where Methods and Properties are made publicly accessible and the internal mechanisms of the class are hidden. The advantage of this is that if a Class has to be modified the rest of the application is isolated from those changes - unless, of course, the definition of the Methods and Properties change. Some languages don't support a mechanism for implementing properties, and so these need to be implemented using public viariables. There are several disadvantages of this mechanism, not least being that it is impossible to make a clean interface which allows data validation of the class properties.

C# allows properties to be defined in a very succinct way. Suppose we want to define a class to represent a book in an application we may identify several properties, for example, Title, Author, Publisher, ISBN etc.

Using public variable fields

Without using properties the definition would be:

public class Book {
  public string Title;
  public string Author;
  public string Publisher;
  public string ISBN;
...
}

Basic property syntax (get/set)

The basic syntax for properties looks like this:

public class Book {
  public string Title { get; set; }
  public string Author { get; set; }
  public string Publisher { get; set; }
  public string ISBN { get; set; }
...
}

The get and set keywords indicate that the field names are to be compiled as properties. This means that the compiler automatically generates private fields, corresponding to the public properties and channels access to them through the public property names. This corresponds to an earlier syntax for C# where the private fields had to be created explicitly. You can still use the old syntax, but it is no longer necessary.

Older syntax with explicit private fields

The obsolete mechanism looks like this:

/* old syntax for property declaration */ 
public class Book {

  private string _title;
  private string _author;
  private string _publisher;
  private string _isbn;

  public string Title {
    get { return _title; }
    set { _title = value; }
  }

  public string Author {
    get { return _author; }
    set { _author = value; }
  }

  public string Publisher {
    get { return _publisher; }
    set { _publisher = value; }
  }

  public string ISBN {
    get { return _isbn; }
    set { _isbn = value; }
  }
...
}

You can still use the older syntax when you need to provide more than just setting and getting operators, for example, if you want to do some processing of the data, or data validation as part of the setting process.

Valid XHTML 1.0! | Valid CSS! | WCAG Approved AA
Page design by: John P Scott - Hosting with: Netcetera