Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
 Auto-Implemented Properties
C# Programming Guide
Auto-Implemented Properties (C# Programming Guide)

Updated: November 2007

Auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field 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:

C#
class LightweightCustomer
{
    public double TotalPurchases { get; set; }
    public string Name { get; private set; } // read-only
    public int CustomerID { get; private set; } // read-only
}

Auto-implemented properties must declare both a get and a set accessor. To create a readonly auto-implemented property, give it a private set accessor.

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.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Attributes are on auto-implemented properties      Atif Aziz   |   Edit   |  

Contrary to the original documentation, attributes are permitted on auto-implemented properties, including their accessors.

public class LightweightCustomer
{
public double TotalPurchases { get; set; }
public string Name { get; set; }
[ XmlAttribute ] public int CustomerID { get; set; }
}

It's possible the documentation meant to say that attributes cannot be applied to the backing fields since these are automatically generated by the compiler, but that would be stating rather the obvious.

Documentation Error      badrhombus ... Noelle Mallory - MSFT   |   Edit   |  

It is not obvious what:

public class ActionTest
{
static void Main()
{
(from i in new[] { 1, 2, 3, 4, 5 }
select i * i)
.ToList()
.ForEach(n => Console.WriteLine(n));
}
}

has to do with Auto-Implemented Properties

Write-only auto-implemented properties      Herenvardo   |   Edit   |  

While it's a marginal case in current practice, auto-implemented properties can be made write-only (a.k.a. data-sinks or black-holes) in a symetryc way to read-only ones. The following code compiles and works as it could be expected:

  namespace MyConsoleApplication {
class Program {
public static string MyWriteOnlyAutoImplementedProperty { private get; set; }
static void Main(string[] args) {
MyWriteOnlyAutoImplementedProperty = "Some text"; // Ok
string MyString = MyWriteOnlyAutoImplementedProperty // Ok: we can still access private members from inside Program

}
}
class MyClass {
public void MyMethod() {
MyWriteOnlyAutoImplementedProperty = "Some text"; // Ok, we are fine as long as we just write
// string MyString = MyWriteOnlyAutoImplementedProperty // Error!

}
}
}

Uncommenting the line marked as "Error!" generates the message "The property or indexer 'MyConsoleApplication.Program.MyWriteOnlyAutoImplementedProperty' cannot be used in this context because the get accessor is inaccessible" at compile time.
The utility of this capability is out of the scope of this comment: it is only intended to point out the existence of the feature.

Tags What's this?: Add a tag
Flag as ContentBug
Auto-generated properties cannot be truly read-only      Dave Sexton   |   Edit   |  

Contrary to what the documentation suggests, it is not possible to define an auto-implemented property that uses the same behavior as the C# readonly keyword (when applied to an explicit backing field). The link to the readonly topic should be removed, at the very least.

Using private set will define an auto-implemented property with a read-only public contract, although this leaves open the possibility for the value to change after the constructor has been invoked; behavior that is prevented by defining a property without a set accessor and applying the readonly keyword to the backing field.

class Class1
{
public string NotReadOnly { get; private set; }
public string TrulyReadOnly { get { return trulyReadOnly; } }
readonly string trulyReadOnly = "value";




public void SetReadOnlyAfterInitialization()
{
// This assignment is permitted by the compiler
NotReadOnly = "this property is not actually read-only.";






// Compile-time error: Property or indexer 'TrulyReadOnly' cannot be assigned to -- it is read only
TrulyReadOnly = "this property is actually read-only.";
}
}
Tags What's this?: Add a tag
Flag as ContentBug
C# 3.0 or newer Only, but not .NET 3.0 or newer only.      Lupo666 ... Thomas Lee   |   Edit   |  
It's not obvious from this page, but I'm assuming this is a feature of C# 3.0. It would have been nice to indicate that in the page's content. The only clue is the droppings in the navigation history.


I've tried to do project in .net 2.0 in VS2008 and Auto properties works, but on VS2005 not.
Maybe VS2008 do something ?
Idea of checking this comes from one the member of .Net group http://slask-msclub.isvclub.com .

Theraot edit: Actually VS2008 does the work, "the compiler creates a private, anonymous backing field" - that - "can only be accessed through the property's get and set accessors." the name of that field is '<PropertyName>k_BackingField' as you can reach it from reflection or MSIL, and It's .Net 2.0 compatible (may be even .Net 1.x compatible, I cannot tell for sure).

[tfl - 15 july 08] - added contentbug to tag list
StructLayout      HWM   |   Edit   |  
Note, that if you take an existing struct and make one or more fields into auto-implemented properties, the field ordering is changed. The layout of fields when auto-implemented properties is NOT The same as it will be when only fields are present.

See bug ID: 360658


Tags What's this?: Add a tag
Flag as ContentBug
Cannot initialize an automatic property      Laughing John ... Sunil SS   |   Edit   |  
Automatic properties would be nice short hand if you could initialize them. You cannot type the following:

public string Name { get; privateset; } = "Fred"

This means that strings and objects always default to null so you have to initialize them elsewhere. This defeats the point of the shorthand syntax.

I have seen the argument that these were added purely for Linq, but if this is the case why does the "prop" snippet produce automatic properties. This makes it even slower to produce a "fully blown" property definition, so things are actually worse than they were. Nice!

Go to Microsoft Connect to vote for the addition of initialization: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361647


Cannot be used to override fields with only a get accessor      Stevo Guy   |   Edit   |  

Probably obvious to most, but when overriding a class with a property that has only a GET accessor, auto-implemented properties cannot be used, as they require both GET and SET.


The use of {get; private set;} is not equivalent, and produces a compile time error.

The behaviour is logical and consistent, but it may be unexpected.