Understanding C# 3.0 Features (1) Automatic Property

[LINQ via C# series]

As the fundamental of LINQ, This chapter will explain the new language features of C# 3.0, all of which are syntactic sugars.

This part is about the automatic property.

In C# 2.0 a property can be declared like this:

public class Person
{
    private string _name;

    public string Name
    {
        get
        {
            return this._name;
        }

        set
        {
            this._name = value;
        }
    }
}

And in C# 3.0 we can use automatic property:

public class Person
{
    public string Name
    {
        get; 
        set;
    }
}

Then the compiler will generate the field definition and accessor definitions for us. The above code will be compiled into:

public class Person
{
    [CompilerGenerated]
    private string <Name>k__BackingField;

    public string Name
    {
        [CompilerGenerated]
        get
        {
            string str = this.<Name>k__BackingField;
            return str;
        }

        [CompilerGenerated]
        set
        {
            this.<Name>k__BackingField = value;
        }
    }
}

It works the same as the first sample. You may noticed:

  • The compiler uses illegal name <Name>k__backingField for the generated field, so that it will never be duplicated by any field defined by us.
  • The getters is a little different from the first sample. In the getter of the first sample, a local variable is not explicitly used. But that getter is actually compiled into:
    get
    {
        string CS$1$0000 = this._name;
        return CS$1$0000;
    }
    So they are exactly the same.

Another sample is, for the purpose of atomic typing, we can write code like this:

public class Person
{
    public Person(string name)
    {
        // Validates the parameter.
        this.Name = name;
    }

    public string Name
    {
        get; 
        private set;
    }
}
Published Thursday, November 26, 2009 1:00 PM by Dixin

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)