Sponsored Ad

Thursday, October 29, 2009

C# 3.0 Language Features

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;
}
}

Or If I want to be really terse, I can collapse the whitespace even further like so:

public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

When the C # "Orcas" compiler encounters an empty get / set property implementation as before, are now automatically generates a private field for you in your class, and implement a public property getter and setter to applying it. The benefit of this is that one type of contract perspective, the class looks exactly like he did with our first application (more details) above. This means that - unlike the public fields - which may in future add validation logic within my property regulator application without having to change any external component that references my class.

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers