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.


4 thoughts on “Is Automatic Property Same as Property?

Leave a Reply

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