Feb 26, 2009

.Net 3.0 - C# - Features and Additions

Some of the interesting and intruiging additions were:
  • Implicitly typed local variables
  • Anonymous types
  • Extension methods
  • Object and collection initializers
  • Lambda expressions
  • Query expressions
  • Expression Trees
  • Linq
Links:
1 http://blah.winsmarts.com/2006/05/17/demystifying-c-30--part-1-implicitly-typed-local-variables-var.aspx
2. Lambda Expressions:
http://blogs.msdn.com/ericwhite/pages/Lambda-Expressions.aspx
3. Lambda Expressions:
http://www.developer.com/net/csharp/article.php/3598381

Feb 9, 2009

C# "Orcas" Language Features (from Scott Guthrie's blog)

Automatic Properties, Object Initializers, and Collection Initializers
-------------------------------------------------------------------------------------------
Automatic Properties
If you are a C# developer today, you are probably quite used to writing classes with basic properties like the code-snippet below:
public class Person

{
private string _firstName;
private string _lastName;
public string FirstName
{
get
{
return rn _firstName;
}
set
{
_firstName = value;
}
}

public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
}
Note about that we aren't actually adding any logic in the getters/setters of our properties - instead we just get/set the value directly to a field. This begs the question - then why not just use fields instead of properties? Well - there are a lot of downsides to exposing public fields. Two of the big problems are: 1) you can't easily databind against fields, and 2) if you expose public fields from your classes you can't later change them to properties (for example: to add validation logic to the setters) without recompiling any assemblies compiled against the old class.
The new C# compiler that ships in "Orcas" provides an elegant way to make your code more concise while still retaining the flexibility of properties using 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 the default get/set operations for you.
For example, using automatic properties I can now re-write the code above to just be:
public class Person

{
public string FirstName
{
get;
set;
}
public string LastName
{
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;
}

How does this work?
Well if I try to decompile the code using Reflector then we would see that we have this following code for the class Personinternal

class Person
{
// Fields
[CompilerGenerated
private string k__BackingField;

[CompilerGenerated]
private string k__BackingField;
// Methods
public Person();
// Properties
public string FirstName
{
[CompilerGenerated]
get;
[CompilerGenerated]
set;
}

public string LastName
{
[CompilerGenerated]
get;
[CompilerGenerated]
set;
}
}
Looks the like the following code was generated by the compiler ... I am still not clear how the "k__BackingField" expression is used in sync with the compiler generated attribute, but I am happy that I have such a shortcut.

N.B.: Those Automatic Properties are even faster to type, when you use Code Snippets:Type "prop", press TAB twice and then just type in the datatype and identifier to the placeholders.
I like also that the classes (typically DTOs) stay clean when using the Automatic Properties.
It is also very easy to copy the properties to interface specifications (or vice versa): just delete or add the access modifiers.

Object Initializers

When the C# "Orcas" compiler encounters an empty get/set property implementation like above, it will now automatically generate a private field for you within your class, and implement a public getter and setter property implementation to it. The benefit of this is that from a type-contract perspective, the class looks exactly like it did with our first (more verbose) implementation above. This means that -- unlike public fields -- I can in the future add validation logic within my property setter implementation without having to change any external component that references my class.
Bart De Smet has a great write-up on what happens under the covers when using automatic properties with the March CTP release of "Orcas". You can read his excellent blog post on it here.
New C# and VB Language Feature: Object Initializers
Types within the .NET Framework rely heavily on the use of properties. When instantiating and using new classes, it is very common to write code like below:
Person person = new Person();
person.FirstName = "Scott";
person.LastName = "Guthrie";

Have you ever wanted to make this more concise (and maybe fit on one line)? With the C# and VB "Orcas" compilers you can now take advantage of a great "syntactic sugar" language feature called "object Initializers" that allows you to-do this and re-write the above code like so:
Person person = new Person { FirstName="Scott", LastName="Guthrie" };


The compiler will then automatically generate the appropriate property setter code that preserves the same semantic meaning as the previous (more verbose) code sample above.
In addition to setting simple property values when initializing a type, the object initializer feature allows us to optionally set more complex nested property types. For example, assume each Person type we defined above also has a property called "Address" of type "Address". We could then write the below code to create a new "Person" object and set its properties like so:
Person person = new Person {
FirstName = "Scott",
LastName = "Guthrie",
Address = new Address
{
Street = "One Microsoft Way",
City = "Redmond",
State = "WA",
Zip = 98052
}
};
Bart De Smet again has a great write-up on what happens under the covers when using object initializers with the March CTP release of "Orcas". You can read his excellent post on it here.

Collection Initializers

New C# and VB Language Feature: Collection Initializers
Object Initializers are great, and make it much easier to concisely add objects to collections. For example, if I wanted to add three people to a generics-based List collection of type "Person", I could write the below code:
List people = new List();
people.Add( new Person { FirstName = "Scott", LastName = "Guthrie" } );
people.Add( new Person { FirstName = "Bill", LastName = "Gates"} );
people.Add( new Person { FirstName = "Susanne", LastName = "Guthrie"} );

Using the new Object Initializer feature alone saved 12 extra lines of code with this sample versus what I'd need to type with the C# 2.0 compiler.
The C# and VB "Orcas" compilers allow us to go even further, though, and also now support "collection initializers" that allow us to avoid having multiple Add statements, and save even further keystrokes:
List people = new List
{
new Person { FirstName = "Scott", LastName = "Guthrie"},
new Person { FirstName = "Bill", LastName = "Gates"},
new Person { FirstName = "Susanne", LastName = "Guthrie"}
};
When the compiler encounters the above syntax, it will automatically generate the collection insert code like the previous sample for us.