If you're a C # on today, probably too used to writing classes with basic properties like the snippet below:
public class Person
{
private string _firstName;
private string _lastName;
private int _age;
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 are not actually adding any logic in the getter / setters of our properties - instead just get / set the value directly to a field. This raises the question - why not just use fields instead of properties? Well - there are plenty of negative aspects of the exposure of public fields. Two major problems are: 1) it is easy DataBind against the fields, and 2) if exposed public fields of classes can not be changed later to the properties (for example: to add validation logic for agencies development) without having to recompile assemblies compiled with the class of age.
The new C # compiler that is included in "Orcas" provides an elegant way to make the code more concise while retaining the flexibility of the building with a new language feature called "automatic properties". Automatic properties allow you to avoid having to manually declare a private field and write the get / set logic - instead the compiler can automate creating the private field and default get / set operations for you.
For example, using automatic properties I can now re-write the code above as given below:
public class Person {
public string FirstName {
get; set;
}
public string LastName {
get; set;
}
public int Age {
get; set;
}
}
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
0 comments:
Post a Comment