New Property Syntax for C# 3.0

C# 3.0 has many new features that have been widely discussed.  LINQ is likely the most talked about language feature in the new version.  One feature that does not seem to be getting much attention is the new syntax for defining properties.  I have seen this referred to as Anonymous Properties, although I am not sure that this is the official name.

I think this is actually going to be one of my favorite language features going forward and it is certainly long overdue.  Anonymous Properties allows the developer to define a variable and make it available as a property, all in statement.  Traditionally, a class with properties is defined as follows:

public class SampleProperties 
{
    private string firstName;
    private string lastname;

    public string FirstName
    {
        get {return firstName;}
        set {firstName = value;}
    }

    public string LastName
    {
        get {return lastName;}
        set {lastName = value;}
    }
}

The above code pattern is recognizable for anyone who has been writing C# at all. Admittedly, it is not a complicated syntax and I much prefer it over the java getter/setter bean pattern. However, Microsoft has added an even more compact syntax for those situations where nothing needs to happen for property getters and setters except the manipulation of the instance variable they wrap:

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

Much better!

Tags: , , , ,

Comments

2 Responses to “New Property Syntax for C# 3.0”

  1. Are Extension Methods Useful for Normal Programming Tasks? : Mostly Progamming Stuff on December 9th, 2007 8:33 am

    […] C# 3.0.  The new language version includes some nice programmer productivity features like Anonymous Properties, Lamda Expressions, and Extension Methods.  I will be concentrating on Extension Methods for this […]

  2. Brij on September 5th, 2011 11:34 am

    Anonymous property is a real good feature for quick programming.