Saturday, July 26, 2008

C# 3.0 Automatic Properties

The C# 3.0 has a very interesting feature: Automatic Properties.

So far, with C# 2.0 and Visual Studio 2005, we have enjoyed the 'Right-Click --> Refactor --> Encapsulate Field' option to automatically generate properties in the classes. And hence, as an example, a User class will look like:

    public class User
    {
        private string userId;
 
        /// <summary>
        /// Gets or sets the user id.
        /// </summary>
        /// <value>The user id.</value>
        public string UserId
        {
            get { return userId; }
            set { userId = value; }
        }
 
        private string userName;
 
        /// <summary>
        /// Gets or sets the name of the user.
        /// </summary>
        /// <value>The name of the user.</value>
        public string UserName
        {
            get { return userName; }
            set { userName = value; }
        }
 
        private string userEmail;
 
        /// <summary>
        /// Gets or sets the user email.
        /// </summary>
        /// <value>The user email.</value>
        public string UserEmail
        {
            get { return userEmail; }
            set { userEmail = value; }
        }
 
        private int userLevel;
 
        /// <summary>
        /// Gets or sets the user level.
        /// </summary>
        /// <value>The user level.</value>
        public int UserLevel
        {
            get { return userLevel; }
            set { userLevel = value; }
        }
    }


Now, with C# 3.0, the User class will look as follows:

    public class User
    {
        /// <summary>
        /// Gets or sets the user id.
        /// </summary>
        public string UserId { get; set; }
 
        /// <summary>
        /// Gets or sets the user name.
        /// </summary>
        public string UserName { get; set; }
 
        /// <summary>
        /// Gets or sets the user email.
        /// </summary>
        public string UserEmail { get; set; }
 
        /// <summary>
        /// Gets or sets the user level.
        /// </summary>
        public int UserLevel { get; set; }
    }


When the code is compiled, the compiler will automatically generate the appropriate fields when encountering the empty get and/or set blocks. However, note that these automatic properties are normally used in situations where no body is in the get or set blocks.

And, going one step further, the compiler generated code for these automatic properties is as follows:

No comments: