C# 3.0 Automatic Properties

13 Dec 2011

C#


There have been quite a few new interesting features added into C# over the last few iterations, and once of these that I'd always wondered about was automatic properties. The syntax is relatively clean, easy and fast to type, but what's happening under the hood? I always wondered whether or not the compiler would be smart enough to mark up my code at build time, however the simply isn't the case at all.

Consider the following code:


public class MyClass 
{ 
    #region Constructors 

    public MyClass(int ID, string Name) 
    { 
        this.ID = ID; 
        sName = Name; 
    } 

    #endregion 

    #region Fields 

    private string sName; 

    #endregion 

    #region Properties 

    public string Name 
    { 
        get 
        { 
            return sName; 
        } 
    } 

    public int ID 
    { 
        get; 
        private set; 
    } 

    #endregion 

    #region Methods 

    public void Update(int ID, string Name) 
    { 
        this.ID = ID; 
        sName = Name; 
    } 

    #endregion 
} 

Now consider the output:


public class MyClass 
{ 
    // Fields
    private string sName; 

    // Methods
    public MyClass(int ID, string Name) 
    { 
        this.ID = ID; 
        this.sName = Name; 
    } 

    public void Update(int ID, string Name) 
    { 
        this.ID = ID; 
        this.sName = Name; 
    } 

    // Properties
    public int ID { get; private set; } 

    public string Name 
    { 
        get 
        { 
            return this.sName; 
        } 
    } 
} 

Here's what's actually happening under the hood:


[CompilerGenerated] 
private void set_ID(int value) 
{ 
    this.<ID>k__BackingField = value; 
} 

[CompilerGenerated] 
public int get_ID() 
{ 
    return this.<ID>k__BackingField; 
} 

Note that the compiler doesn't mark up the property at all, there is still a method call to the private set method. So, in short, your code is still going to execute faster if you declare your properties yourself, and as declaring your own properties isn't difficult or time consuming, it's a no brainer.


 

Copyright © 2024 carlbelle.com