Monday, February 11, 2008

C# 3.0: Explained: Implicitly Typed Local Variables

C# 3.0 brings lots of new extensions C# 2.0. The extensions are:

  • Implicitly typed local variables
  • Extension methods
  • Lamda Expressions
  • Object initializers
  • Anonymous Types
  • Implicitly typed arrays
  • Query Expressions
  • Expression Trees
Download the Official C# 3.0 Language Specification from Microsoft.

I will do my best to cover all of these advanced topics.

Implicitly typed local variables

Implicitly typed local variables are automatically inferred by compiler to their corresponding strong types.

var name = "Hemanta Sapkota";
var id = new string[] { "1", "2" };
var myList = new List<string>();

Notice the var keyword is used. Remember the above is same as doing:

string name = "Hemanta Sapkota";
string[] id = new string[] { "1", "2" };
List<string> myList = new List<string>();

The code below illustrates common correct use and restrictions to using implicitly typed local variables.

class Program
{

var notLegal; //Error. Cannot declare non-local var

static
void Main(string[] args)
{
//correct use
var name = "Hemanta Sapkota";
var id = new string[] { "1", "2" };
var myList = new List<string>();
var var = 32; //creating a variable with the name 'var' is allowed

var = 45; //here 'var' refers to the var type we created above. This is allowed.

//Error.
var l1 = "name", l2 = "none"; //cannot have multiple declarators
var col = { 'a', 'b', 'c' }; //Collection initializer not permitted
var notNull = null; //Cannot assign to an implicitly-typed local variable
var alsoNotLegal; //Implicitly-typed local variables must be initialized
alsoNotLegal = String.Empty;

var v1 = "taxi";
var v2 = 45.6;
v1 = v2 = "error"; //cannot implicitly convert type 'string' to 'double'

}

}

Implcitly typed local variables can also be used with for-initializer, and foreach. Consider:

var myList = new List<string>();

myList.Add("Item1");
myList.Add("Item2");
myList.Add("Item3");

foreach (var str in myList)
{
System.Console.WriteLine(str);
}

Likewise implicitly typed local variables can also be used with the using statement.
In the next post, i will talk about Extension Methods.



No comments: