As my quest to understand the finer details of LINQ which I would present to my team at Imageright, I thought it would be a great idea to start from scratch and look at each functionality of C# language which enables LINQ. In that process, I start with Auto-implemented Properties.
Defining auto-implemented property
The above class Person, defines an auto-implemented properties. you see can see both setter and getter defined. We will dig more into these in a while before which we should look at the compiler generated code. I used Reflector to decompile the source and this is what it looks like.
Clearly, nothing exceptionally new has been added to the IL and the compiler just generates C# 2.0 like properties from the above property – thus aptly named auto-implemented properties. Notice that a hidden backing field is used to support the property.
CompilerGeneratedAttribute[System.Runtime.CompilerServices] is applied to any element that is not user written and is automatically generated by the compiler. This attribute can be used to determine if an element is generated by the compiler.
The above shown way is INCORRECT. The compiler does not allow readonly keyword on the auto-prop. The way you achieve read-only is as shown below.
The compiler generated code seems to add “private’ before the setter, just like the way we did.
As a side-note, auto-implemented properties can also be static.
Well, this might not make sense to use (in practical scenarios), but write-only properties are also allowed. When one tries to read a write-only property, the compiler generates the following error.
Error 1 The property or indexer 'LinqBasics.Person.SecretCode' cannot be used in this context because the get accessor is inaccessible
Shown below is a write-only property.
Also note that, you can re-order the get and set [does not matter, though].
What are not allowed?
The accessibility modifier for the accessor should be more restrictive than the property or the indexer.
The following property is invalid.
Similarly, a private property cannot have a public accessor.
You cannot specify accessibility modifiers for both accessors of a property or indexer.
The following is invalid.
Indexers cannot be defined using auto-implemented properties.
If you do so, you end up with compiler error
Automatically implemented properties must defined both get and set accessors.
The following is not valid.
Normal properties can be initialized, while auto-implemented properties cannot be initialized.
See the code below.
The documentation also talks about creating immutable classes using auto-implemented properties. So, now lets make the Person class immutable (we make all the properties as read-only and privatize the constructor. also we provide a factory method for instantiation.)
I will add more information later if required. I hope this article is as informative as I wanted it to be.