Is Automatic Property Same as Property?

I was listening one session on TechEd (night after long party, yeah) and I was thinking about automatic properties – are they really exact equivalent to usual properties? Something made me suspicious, so I opened my laptop at first free moment and checked out what’s going on.

At first let’s write a little class. We will use it later to play with automatic properties.


public class AutoPropTest
{
   
private string
name;
   
public string
Name
    {
       
get { return
name; }
       
set { name = value
; }
    }

   
public string Name2 { get; set; }
}

This class has one usual property (Name) and one automatic property (Name2). Now let’s compile this class and let’s see how this class looks in Reflector after compiling.


public class AutoPropTest
{
   
// Fields
    [CompilerGenerated
]
   
private string
<name2>k__BackingField;
   
private string
name;

   
// Methods
    public
AutoPropTest();

   
// Properties
    public string Name { get; set
; }
   
public string
Name2 {
        [
CompilerGenerated] get
;
        [
CompilerGenerated] set;
    }
}

Looking at the code we can see that usual property and automatic property are not synonyms of each other. Automatic property has unaccessible attribute to hold value. Also we can see there CompilerGeneratedAttribute that usual properties doesn’t have.

To be honest, automatically generated attribute is not unaccessbile – you can access it using reflection. Although I see no point why someone should access this attribute directly.



See also

3 thoughts on “Is Automatic Property Same as Property?

  • Paymon says:

    It depends.

    If the field that holds the value needs to be used inside the class very frequently, then performance-wise, automatic property is not the answer:

    Every single “Get” means calling a getter method, pushing on the stack, etc.

  • Lee says:

    Is it a significant performance hit to the getter every time you need to reference the value? Just curious, I haven’t done any benchmarking or anything.

  • Manish Batra says:

    Looking closely to the Disassembler, compiler has created a private instance “k__BackingField” by itself for automatic property. This way, we have increased the compiler overhead and shouldn’t be considered under best practice.

Leave a Reply

Your email address will not be published. Required fields are marked *