Cool new C# syntactic sugar


Just the other day I ranted about all the explicit get; set; implementation and I found this out today.

I was reviewing some code and I saw something like this

class MyClass
{
    public int Property {
        get; set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();
        mc.Property = 42;
        Console.WriteLine(mc.Property);
    }
}

I was completely confused. How the hell is there a abstract property in a concrete class? Then I figured out that this is new short-hand supported by Visual Studio 2008 (code-named Orcas and you can check this out in the latest beta).

The compiler generates the field for the property and also generates the code in the get set to point to the field.

internal class MyClass
{
    // Fields
    [CompilerGenerated]
    private int <Property>k__BackingField;

    // Properties
    public int Property
    {
        [CompilerGenerated]
        get
        {
            return this.<Property>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            this.<Property>k__BackingField = value;
        }
    }
}

Comments (10)

  1. DanielMoth says:

    FYI, the "syntactic sugar" feature has a name 🙂

    Automatic Properties

    (aka auto-implemented properties)

  2. Thierry says:

    What is the use of this feature, except perhaps the ability to set a breakpoint?

  3. FxCop guideline is to wrap publicly visible fields in properties. Hence you land up writing a lot of these call only Properties. The Automatic Property will help in that.

    Remember you cannot change a field to a Property later because all assemblies referring to it will have to be recompiled (see http://blogs.msdn.com/abhinaba/archive/2006/04/11/572694.aspx) .

  4. It should be noted that if you are going to serialize any of these classes, then it is a bad idea to use the auto implemented properties.

  5. Raj Kaimal says:

    Note that you can also do this:

    public int Property {

           get; private set;

       }

  6. DanielMoth says:

    Thierry, in addition to the versioning issue that Abhinaba points out, fields aren’t always bindable whereas properties are.

  7. I’ve blogged about this being the "Lamest New Feature in C# 3.0".  http://wekempf.spaces.live.com/blog/cns!D18C3EC06EA971CF!234.entry

    It really is a waste of syntactic sugar.

  8. Rujith says:

    Well I would say as a programer, I hate this feature.

  9. John says:

    I have to agree with Rujith. To me it just seems like a lazy feature for a lazy programmer.

  10. Marv says:

    the less code, the less errors, good thinking Microsoft…