Monday, May 26, 2008

Some of C# 3.0's new features

C# 3.0 provides many new technologies, recently I became aware of some of the syntax improvements. This post is intended to outline some of the highlights.

Auto Implemented Properties
One new feature in C# 3.0 is “Auto Implemented Properties”, this is a fancy way of saying that we no longer have to create the private property and the public fields when we write new classes. Take a look at the below example:

private string userId;
Public String UserId
{
get { return userId; }
set { userId = value; }
}

IS the same as

public string UserId {get;set;}

The compiler will write out the needed getters and setters, however, they need not be in the source code unless a more complex structure is needed. The net effect is 5 less lines of code per property.

Object initializers
Another new feature is known as “Object Initializers”, this is a means to allow programmers to set values that aren’t part of the constructor at init time. Take a look at the below example:
Customer c = new Customer(“john”,”doe”);
c.phone=”123-456-7890”;
c.zip = “43534”;

is the same as

Customer c = new Customer(“john”,”doe”) {phone=”123-456-7890”,zip=”43534}

This may seem insignifigant, however, it is not. There are many classes I have come in contact with that have properties that aren’t set in the constructor. In these cases you must make additional statements to set the further needed properties. That limitation is now removed, you can now set those properties all at once. This again, it a little compiler trickery, at compile time they are broken out into individual statements just as you would have, but as with the auto implemented properties, this is an improvement in the overall readability, serviceability, and cleanliness of the source code. I a way this reminds me of how you can add items into an array at the time of declaration
string[] x = new string[]{“a”,”b”,”c”};

Local Variable Type Inference
Microsoft has seen the complaints that the following just looks a little odd:
Customer customer = new Customer();
Their answer is called local variable type inference using the var keyword. What this means that the following will now be accepted:
var customer = new Customer();
In this case the compiler detects the type from the new Customer() part of the statement. I cant say this is a whole lot shorter or neater in most case, however, when using linq, the type is not known as types are created on the fly to support the data requested. So it does seem to be useful in the linq arena.

More thoughts as they come in.

No comments:

Post a Comment