Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Auto-Implemented Properties

Tags:

c#

.net

I am fairly new to auto-implemented properties and for the most of it I find them pretty straight forward but in the Microsoft site it states:

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.

-- Auto-Implemented Properties (MSDN)

Can anyone explain what the following statement actually means with regard to auto-implemented properties: "They also enable client code to create objects."?

I cannot figure out what this means.

Thanks.

like image 547
skeandu Avatar asked Aug 02 '11 12:08

skeandu


2 Answers

I believe this refers to object initializer syntax, though why this would be the case is not clear. Auto implemented properties and object initializers are separate things and shouldn't be linked together this way.

So, with a class that looks like this:

public class Cat
{
    // Auto-implemented properties.
    public int Age { get; set; }
    public string Name { get; set; }
}

You can create objects like this:

Cat cat = new Cat { Age = 10, Name = "Fluffy" };

Note:

As the comments say (and the MSDN page on object initializers declares), you can use object initializer syntax with any accessible field or property. Again, the fact that the MSDN page on auto-implemented properties even mentions object creation appears to be a bad documentation decision.

like image 75
Oded Avatar answered Sep 23 '22 22:09

Oded


That's a bad description on the MSDN page, unfortunately.

Object initializer syntax (new Foo { X = 10, Y = 20 }) is completely separable from automatically implemented properties.

Object initializers can be used with any settable properties or fields (and there's even syntax for mutating "subproperties" when the "main property" is read-only); you don't have to use an automatically implemented property for this.

While it's nice that all these features work together, I believe it's useful to at least learn about them separately. For example, automatically implemented properties could have been introduced in C# 2 without object initializers - or vice versa.

like image 26
Jon Skeet Avatar answered Sep 23 '22 22:09

Jon Skeet