class Car
{
public string Speed { get; set; }
}
Why Auto-Implemented
Properties?
Looking back the way that we have been doing for creating a property
in so many projects, do you notice that you have been writing so
many line codes just for creating a simple property? Look at the code
below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
_firstName = value;
}
}
public string LastName {
get {
return _lastName;
}
set {
_lastName = value;
}
}
}
time for declaring private variable, setting the value to that private
variable and returning the value.
Take a look at the class that I have converted from normal class (Code
1.0) to the class with auto-implemented properties. Its much shorter,
right?
1
2
3
4
5
6
class Employee
{
public int ID{ get; private set; } // read-only
public string FirstName { get; set; }
public int LastName { get; set; }
}
Conclusion
Auto-Implemented Properties is one of the most popular features of
C# 3.0 and a lot of developers are really happy with that new feature.
but you should know that auto-implemented properties are nothing
new except it helps you to boost your productivity.
FAQs
1. Can Auto-implemented Properties improve the performace?
No. It is just helping you to type shorter code but it doesnt improve
the performance since the compiler will generate the same as the way
what it generates for normal class that doenst have auto-implemented
properties.
2. How can I make read-only or write-only auto-implemented
properties?
You can make the accessor as private. For example: If you want to
make read-only property then You can put private in setter. You
can read more about that in C# 3.0 specification.
It mentioned like below in C# 3.0 specification ~
When a property is specified as an automatically implemented
property, a hidden backing field is automatically available for the
property, and the accessors are implemented to read from and write to
that backing field.
Because the backing field is inaccessible, it can be read and written
only through the property accessors. This means that automatically
implemented read-only or write-only properties do not make sense,
and are disallowed. It is however possible to set the access level of
each accessor differently. Thus, the effect of a read-only property
with a private backing field can be mimicked like this:
1
2
3
4
5
public
public
public
public
}
class ReadOnlyPoint {
int X { get; private set; }
int Y { get; private set; }
ReadOnlyPoint(int x, int y) { X = x; Y = y; }