Wednesday 17 October 2007

Part 2: Automatically implemented properties

C#2 provides the ability to create properties that encapsulate class member variables; the following code provides a simple example:

//Private member variable to store the client name
private string name;

//Read-write property for the client?s name
public string Name
{
    get
    {
        return name;
    }
    set
    {
        name = value;
    }

The idea here is that the property prevents the class variable from being accessed directly. A property can be made read only as follows; this is simply a property that does not have a set statement.

// Read only property that returns the client?s name
public string Name
{
    get
    {
        return name;
    }

C#3 provides a shortcut syntax for creating class variables and associated properties; the first code example can be shortened to:

// Shortcut syntax for creating properties
//and underlying member variables
public string Name { get; set; } 

And of course, the principle of read only (or write only for that matter) properties is also supported using this new syntax:

// Shortcut syntax for creating properties and underlying
//member variables (this time ClientName is read-only)
public string Name { get; private set; }

For this shortened syntax, the compiler actually generates all of the required code behind the scenes. So in effect, you end up with exactly the same code that you would have got if you had written it using the available syntax of C#2. The code below shows the MSIL that is generated from the source code; note the use of the [CompilerGenerated] attribute that decorates the code.

[CompilerGenerated]
private string k__BackingField;

public string Name
{
     [CompilerGenerated]
     get
     {
         return this.k__BackingField;
     }
    [CompilerGenerated]
    set
    {
        this.k__BackingField = value;
    }
}

Automatically implemented properties provide a way to quickly expose class member variables; we will examine this feature more in the next article.

Part 3: Initialising objects

 

No comments: