Tuesday, March 3, 2009

C# 3.0 features that clean up (a bit) the code

I work to a new feature (so stay tuned!) but I wanted to describe some features that are used in NaroCad and are specific to C# 3.0 (part of .NET 3.5 and Visual Studio 2008).

We don't use LinQ and lambda expressions for now but some features may interest other developers when they have to handle our code:
1. The var keyword
Old code
SortedDictionary<int,Node> _childNodes = new SortedDictionary<int,Node>();
New code:
var childNodes = new SortedDictionary<int,Node>(); (the compiler will decide the type, and the code is equivalent)
var removes a long left side declaration and it is shorter than most types you can define. The issue is that using var keyword extensively you will not be able to decide which type you run.
var x = f(); //where f returns a type int
x = 3.1415; // it will give to you a compile error as you want to use it as a float type
//but is declared as int

2. Automatic created properties:
Old code:
class Line2d
public Vertex3d Vertex1
get {return _vertex1; }
set { _vertex1 = value; }
//internal member class to reflect the properties
Vertex3d _vertex1;

The new code is only this:
class Line2d
public Vertex3d Vertex1 { get; set; }

If you will know other tricks or hints, add comments down!

No comments: