First posted at: http://blogs.microsoft.co.il/blogs/maordavid/archive/2007/09/26/c-automatic-properties.aspx
Visual Studio 2008 and .NET 3.5 introduces us new feature: Automatic Properties.
You probably write classes with properties like this:
1: public class Student
2: {
3: private string _firstName;
4:
5: public string FirstName
6: {
7: get { return _firstName; }
8: set { _firstName = value; }
9: }
10:
11: private string _lastName;
12:
13: public string LastName
14: {
15: get { return _lastName; }
16: set { _lastName = value; }
17: }
18:
19: private string faculty;
20:
21: public string Faculty
22: {
23: get { return faculty; }
24: set { faculty = value; }
25: }
26:
27: }
Usually, you aren't actually adding any logic in the getters/setters of your properties - instead you just get/set the value directly to a field.
Basically, automatic properties allow you to replace this common pattern with this one:
1: public class Student
2: {
3: public string FirstName
4: {
5: get; set;
6: }
7:
8:
9: public string LastName
10: {
11: get; set;
12: }
13:
14:
15: public string Faculty
16: {
17: get; set;
18: }
19: }
No fields, only properties and declarations of get/set. The compiler can automate creating the private field and the default get/set operations for you.
This is certainly much more compact and requires fewer steps. When the compiler sees this class, (according to Reflector) it translates it to:
public class Student
{
// Fields
[CompilerGenerated]
private string <Faculty>k__BackingField;
[CompilerGenerated]
private string <FirstName>k__BackingField;
[CompilerGenerated]
private string <LastName>k__BackingField;
// Methods
public Student();
// Properties
public string Faculty { [CompilerGenerated] get; [CompilerGenerated] set; }
public string FirstName { [CompilerGenerated] get; [CompilerGenerated] set; }
public string LastName { [CompilerGenerated] get; [CompilerGenerated] set; }
}
There are a few things to look out for when using this syntax. The compiler forces you to declare properties with both a get and a set. You also don't get any kind of "safety" features, such as ensuring that you don't allow a null value to be assigned to a string property. If you want these more "advanced" features, you'll still need to define your property with the "old way".
No comments:
Post a Comment