PDA

View Full Version : Sample Code C# 3.0 : Implicitly Typed Local Variables


Kreij
03-23-2008, 05:45 PM
C# 3.0 (VS2008) has added some new features, one of which I mentioned in an earlier thread (Lamba Expressions).

Another feature that they have added is “Implicitly Typed Local Variables”.
Local variable can now be assigned using the var keyword.
When assigning a variable as type “var”, the compiler infers the type of variable from the expression on the right side of the initialization statement.

var myVar = 5; // this is compiled as an Int
var myVar = “Whassup?”; // this is compiled as a string

Some of you may think this is just a “Variant” type and subverts the notion of strongly-typed, safe variables. It's not. The variable is still strongly-typed (as in Int myVar = 5; ), it's just that the compiler does the typing for you. It's basically a syntactical convenience.

Note, however, that it goes beyond simple variables. It can be used to assign just about anything.

var myVar = new[] {1, 2, 3, 4); // compiles as Int[]
var myVar = new {Name = “Kreij”, Site = “TPU”};
// compiles as an anonymous type containing two field members.

Let's say that you create a type that is enumerable (uses the IEnumerable interface) called Customers that contains several member fields. Two of which are CustomerName and CustomerLocation.

var myVar = from c in Customers where c.CustomerLocation == “Chicago” select c;

The above will compile as a “IEnumerable<Customer>” type.
You can then declare another var to enumerate through the first.

foreach (var record in myVar)
{
console.Writeln(“Customer Name = {0}”, record.CustomerName);
{

This will give you all customer names in Chicago.

As you can see, this syntactical shortcut will ease the carpal tunnel of many a programer :)

There are a few caveats, however ...

You cannot initialize the variable to null
var myVar = null; //Error
You cannot use them is class scope

public class myClass
{
var myVar = 5; //Error

public myClass ()
{
}
}

They cannot be used in the initialization expression.
var myVar = myVar++; //Error
You cannot do multiple initializations.
var myVar = 5, myVar2 = "Whassup?"; // Error
If you create a local variable name “var” in scope, the compiler will throw an error if you try to use the “var” keyword.

Int32 var = 5;
var myVar = 10; // Error


Just so you know here is the recommendation from MS on this ...
However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

Have fun coding !!