Gunnar Peipman's ASP.NET blog

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.

Comments

rascunho » Blog Archive » links for 2008-03-13 said:

Pingback from  rascunho  &raquo; Blog Archive   &raquo; links for 2008-03-13

# March 13, 2008 4:32 PM

Paymon said:

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.

# March 14, 2008 10:00 AM

Lee said:

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.

# March 18, 2008 5:08 PM

access synonyms said:

Pingback from  access synonyms

# April 11, 2008 11:00 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)