New C # language features: Automatic Properties)
If you are a C # developer, you may be very accustomed to writing types with basic attributes like the following code snippet:
Public class Person {
// Declare the private field in the Person class
Private string _ firstName;
Private string _ lastName;
Private int _ age;
// Implement attribute operations
Public string FirstName {
Get {
Return _ firstName;
}
Set {
_ FirstName = value;
}
}
Public string LastName {
Get {
Return _ lastName;
}
Set {
_ LastName = value;
}
}
Public int Age {
Get {
Return _ age;
}
Set {
_ Age = value;
}
}
}
Note that we didn't actually add any logic to the geter/setter of the attribute. We just implemented get/set to a member variable. We can't help but ask the following question: why don't attributes be used directly without member variables? This is because there are a lot of bad things to expose member variables to the outside. The two biggest problems are: 1) You cannot easily bind data to member variables; 2) If you present member variables outward from the class, without re-compiling any assembly that references the old class, you cannot change them to attributes (for example, you need to add the verification logic to setter ).
The new C # compiler released in Orcas provides an elegant way to make your encoding more concise through a language feature called "automatic properties, at the same time, it also maintains the flexibility of attributes. Automatic attributes allow you to avoid manually declaring a private member variable and writing the get/set logic. Instead, the compiler automatically generates a private variable and default get/set operation for you.
For example, using automatic attributes, I can rewrite the above Code:
Public class Person {
Public string FirstName {
Get; set;
}
Public string LastName {
Get; set;
}
Public int Age {
Get; set;
}
}
Or, if I want to be more concise, I can further compress the blank space, like this:
Public class Person {
Public string FirstName {get; set ;}
Public string LastName {get; set ;}
Public int Age {get; set ;}
}
When the C # compiler in Orcas encounters an empty get/set attribute like above, it will automatically generate a private member variable for you in the class, implement a public getter and setter for this variable. The advantage of doing so is that from the perspective of type-contract, this class looks exactly the same as the first lengthy implementation above, which means that, unlike publicly available member variables, in the future, I can add verification logic in the setter implementation of my attributes without modifying any external components that reference my classes.
Bart De Smet gives a wonderful description of the internal situation when using the automatic attributes of the CTP version of Orcas in September March. You can read this wonderful post here.