5 out of 11 rated this helpful - Rate this topic

Auto-Implemented Properties (C# Programming Guide)

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

The following example shows a simple class that has some auto-implemented properties:



// This class is mutable. Its data can be modified from
// outside the class.
class Customer
{
    // Auto-Impl Properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

    // Constructor
    public Customer(double purchases, string name, int ID)
    {
        TotalPurchases = purchases;
        Name = name;
        CustomerID = ID;
    }
    // Methods
    public string GetContactInfo() {return "ContactInfo";}
    public string GetTransactionHistory() {return "History";}

    // .. Additional methods, events, etc.
}

class Program
{
    static void Main()
    {
        // Intialize a new object.
        Customer cust1 = new Customer ( 4987.63, "Northwind",90108 );

        //Modify a property
        cust1.TotalPurchases += 499.99;
    }
}


The class that is shown in the previous example is mutable. Client code can change the values in objects after they are created. In complex classes that contain significant behavior (methods) as well as data, it is often necessary to have public properties. However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, it is recommended to make the objects immutable by declaring the set accessor as private. For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties (C# Programming Guide).

Attributes are permitted on auto-implemented properties but obviously not on the backing fields since those are not accessible from your source code. If you must use an attribute on the backing field of a property, just create a regular property.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Re: Why use Auto-Implemented Properties?
In reply to  Monjjindo : it is a good habit to hide as much as possible, but it is also a good habit to write readable code. And writing readable code means that important things should stand out. $0$0 $0 $0With the "old" syntax, each property needed at least 6 lines of code (instead of one for a simple public variable). A simple class definition can easily spread on three pages with the first two and a half being mostly noise. Most of the time, you have to go at the bottom of the file to see the "real" code.$0 $0$0 $0 $0I have saw thousands of such messy classes, but I really seldom saw someone changing a set or a get...$0 $0$0 $0 $0A lot of developers know the good coding habits. Unfortunalty, too few know that there is always a trade-off : isolating is good but it come with complexity, who is not. I would isolate attributes in a widely distributed framework, but I would not do it systematically in the presentation layer of an in-house development, for example...$0 $0$0 $0 $0Note : Fortunalty, the auto property syntax remove all the noise :)$0
reference: How do you give a C# Auto-Property a default value?
this stackoverflow question and its answers are worth viewing:
"How do you give a C# Auto-Property a default value?"
http://stackoverflow.com/questions/40730/how-do-you-give-a-c-auto-property-a-default-value
Re: Why use Auto-Implemented Properties?
In reply to Manoj Garg, there are a couple reasons why you would want to use properties instead of public fields. $0$0 $0 $01. It's a good programming practice.$0 $02. If you use reflection at all to work with your object, then changing the definition in the future from a field to a property may break that code.$0
why use Auto-Implemented Properties??
One thing a programmer can think is what is difference between auto implemented properties like "publicdouble TotalPurchases { get; set; }" and public field like "public double TotalPurchases" as both have same accessibility? If you want to put code in it(get or set) then properties are justified but what about above case. Some say it helps if in future you need to write some code in either or both of get and set methods. But in that case too a programmer can change field name with property and implement property like change "TotalPurchases" to "_totalPurchases" and create property "publicdouble TotalPurchases { get; set; }". So what's the use?
But there is very subtle difference between the above two implementations. Properties are methods not fields so what they return is not same field but the copy of the original data (copy in case of value types and reference in case of reference types). So if you copy the reference types return value in a variable then you can change the value of field by manipulating your variable's content but still can't change its reference which is quite possible if you don't use properties.

Private vs. read-only automatic property

Does not allow the parent class to set the property:
public string UserName { get; }


Allows parent class to set property:
public string UserName { get; private set; }
Read-only properties
In response to rmalves: Another way to make it read-only would be to leave out "set;" all together.

public string UserName { get; }

Advertisement