Jaa


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

  • Anonymous
    September 20, 2007
    FYI, the "syntactic sugar" feature has a name :-) Automatic Properties (aka auto-implemented properties)

  • Anonymous
    September 20, 2007
    What is the use of this feature, except perhaps the ability to set a breakpoint?

  • Anonymous
    September 20, 2007
    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) .

  • Anonymous
    September 21, 2007
    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.

  • Anonymous
    September 21, 2007
    Note that you can also do this: public int Property {        get; private set;    }

  • Anonymous
    September 21, 2007
    Thierry, in addition to the versioning issue that Abhinaba points out, fields aren't always bindable whereas properties are.

  • Anonymous
    September 23, 2007
    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.

  • Anonymous
    September 23, 2007
    Well I would say as a programer, I hate this feature.

  • Anonymous
    September 27, 2007
    I have to agree with Rujith. To me it just seems like a lazy feature for a lazy programmer.

  • Anonymous
    November 13, 2007
    the less code, the less errors, good thinking Microsoft...