June 16th, 2008 - by Golgotha

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:
private string _Name;

public string Name
get {return _Name;}
set {_Name = value;}

Now here’s the code using automatic properties:
public string Name {get; set;}

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:
Customer Mark = new Customer();
Mark.Id = 12;
Mark.Kids = 2;
Mark.Money = 1000000.00m;

We can do this:
Customer Mark = new Customer {Id=12, Kids=2, Money=1000000.00m};

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#:

var message = “Hello World!”;

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.

3 Responses to “3 C# 3.0 Shortcuts”

1 Jack

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. 🙂

2 Golgotha

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.

3 ilovecode » Reasons to Choose .NET 3.5 Over 2.0

[…] 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 […]

mulberry sale spyder womens jacket cheap new balance 574 mulberry outlet cheap new balance 574 arcteryx outlet mulberry sale spyder womens jacket mulberry sale spyder womens jacket mulberry outlet mulberry outlet new balance 574

Popular Articles

Top 10 Commentators

Subscribe to this feed! Subscribe by Email!

Random Bits Podcast

You need to download the Flash player from Adobe

Other Sites