11.2.Creating Auto-Implemented Properties

The patterns you see here, where a property encapsulates a property with get and set accessors, without any other logic is common. It is more code than we should have to write for such a common scenario. That’s why C# 3.0 introduced a new syntax for a property, called an auto-implemented property, which allows you to create properties without get and set accessor implementations. Listing 10-5 shows how to add auto-implemented properties to a class.
Listing 10-5. Auto-Implemented Properties

using System;
publicclass Customer
publicint ID { get; set; }
publicstring Name { get; set; }

publicclass AutoImplementedCustomerManager
staticvoid Main()
        Customer cust = new Customer();

        cust.ID = 1;
        cust.Name = "Amelio Rosales";

"ID: {0}, Name: {1}",


Notice how the get and set accessors in Listing 10-5 do not have implementations. In an auto-implemented property, the C# compiler creates the backing store field behind the scenes, giving the same logic that exists with traditional properties, but saving you from having to use all of the syntax of the traditional property. As you can see in the Main method, the usage of an auto-implemented property is exactly the same as traditional properties, which you learned about in previous sections.
You now know what properties are for and how they’re used. Traditional techniques of encapsulation have relied on separate methods. Properties allow you to access objects state with field-like syntax. Properties can be made read-only or write-only. You also learned how to write properties with less code by using auto-implemented properties.

Yes No Suggest edit
Suggest Edit