1. Automatic Properties
Automatic properties provide you with a shorthand for defining a new property. No more do we have to create the private property and then use Getters and Setters to access and set that property. Here’s the old code:
[ASP]
private string _Name;
public string Name
{
get {return _Name;}
set {_Name = value;}
}
[/ASP]
Now here’s the code using automatic properties:
[ASP]
public string Name {get; set;}
[/ASP]
Oh my! How nice is that? The C# compiler creates the Getters and Setters and the private fields for you automagically!
2. Initializers
We’ve talked about initializers before, but let’s review anyway. You can use initializers to reduce the amount of work it takes to create a new instance of a class. Instead of this:
[ASP]
Customer Mark = new Customer();
Mark.Id = 12;
Mark.Kids = 2;
Mark.Money = 1000000.00m;
[/ASP]
We can do this:
[ASP]
Customer Mark = new Customer {Id=12, Kids=2, Money=1000000.00m};
[/ASP]
Short and sweet — the way I like it.
3. Type Inference
This new feature takes a page out of JavaScript’s book. When you take advantage of type inference, you allow the C# compiler to determine the type of variable at compile time. Here’s an example of how you use type inference with C#:
[ASP]
var message = “Hello World!”;
[/ASP]
Looks like JavaScript eh? Notice that we didn’t declare a type? The C# compiler can infer the type of variable (it’s a string) from the value you use to initialize the variable.
No performance impact results from using type inference. The compiler does all the work figuring out the data type at compile time.
Notice the use of the keyword var? You declare a variable of type var when you want the compiler to figure out the variable’s data type all by itself.
Enjoy those three shorthand shortcuts and happy coding.
June 17th, 2008 at 5:17 am
Hey, didn’t know you were into C#…I’ve been busy myself writing a bit of C# code too. Take a look at PowerTime (a pure C# time series database) over at google code http://code.google.com/p/powertime/
Its currently in alpha but I’m working on it. Soon be alpha 2. 🙂
June 17th, 2008 at 8:13 am
Hey Jack, yeah, I’m back in the C# world. I was using Java the last 6 months doing contract work, but now I have a new job that is using .NET so I am reintroducing myself to C# and looking at some on the new 3.5 stuff.
October 26th, 2008 at 2:52 pm
[…] decent list and a few blogs in particular really helped explain the benefits such as Mark’s C# Shortcuts and Scott Guthrie’s Summary on Visual Studio 2008 and .NET […]