RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


What's New in C# 3.0? Part 1

The release of Visual Studio 2008 updates C# to version, 3.0, with several key language enhancements and LINQ support. Part one of this series will walk you through implicit typing, automatic properties, and other time-saving enhancements.

ith the release of Visual Studio 2008, Microsoft has updated the C# language to its latest version, 3.0. C# 3.0, contains several key language enhancements that support the recently-announced Language Integrated Query (LINQ) feature. This article, the first of a two-part series, will walk you through each of these new, time-saving language enhancements and provide a couple of code examples illustrating how to use them.

Implicit Typing
In the previous version of C#, all variables must be explicitly typed/declared. For example, suppose you want to declare a string variable. You'd do this:

   string str = "Hello World";
In C# 3.0, this is not mandatory. You can use the new var keyword to implicitly declare a variable. Consider the following statements:

   var str = "Hello world!";
   var pt = this.Size;
Here, str is implicitly declared as a string variable, while pt is implicitly declared as a Size variable. The type of variable declared is based on the value with which it is initialized. This method of variable declaration is known as Implicit Typing. Note that implicitly-type variables must be initialized when they are declared. The following statement will not compile:

   var str;  //---missing initializer---
Also notice that IntelliSense will automatically know the type of the variable declared, as you can see in Figure 1.

Figure 1. IntelliSense Knows: IntelliSense automatically infers the type of variable from the initialized value.12a5.

You can also use implicit typing on arrays. For example, the following statement declares points to be an array containing two Point objects:

var points = new[] { new Point(1, 2), new Point(3, 4) };
When you use implicit typing on arrays, make sure all the members in the array are of the same type. The following won’t compile since its members are of different types—string and Boolean:

var arr = new[] { "hello", true, "world" };
Implicit typing is useful in cases where you do not know the exact type of data you're manipulating and you need the compiler to determine for you. Do not confuse the Object type with implicit typing. Variables declared as Object types need to be casted during runtime and IntelliSense does not know this type during development time. On the other hand, implicitly-typed variables are statically typed during design time—hence, IntelliSense is able to provide detailed information about the type. In terms of performance, an implicitly typed variable is no different from a normal typed variable.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date