Wednesday, May 21, 2008

Implicitly typed local variables (var – Contextual Keyword)

Implicitly typed local variables (var – Contextual Keyword)

Suppose I have created console application named ExplicitVars. Code given below all the variables are known as explicitly defined.

static void ExplicitVars()
{

// Explicitly typed local variables
// are declared as follows:
// dataType variableName = initialValue;

int ExplicitInt = 0;
bool ExplicitBool = true;
string ExplicitString = "go catch it...";
}

C# has introduced new token known as "var" which can decide the data type of the variable based on the value assigned to it. Above mention code can be written as.

static void ImplicitVars()
{

// implicitly typed local variables
// are declared as follows:
// var variableName = initialValue;

var ImplicitInt = 0;
var ImplicitBool = true;
var ImplicitString = " go catch it...";
}


When you see the types of each variable defined above it will be converted automatically by compiler based on the value assigned to it.

static void ImplicitVars()
{

// Implicitly typed local variables.
var ImplicitInt = 0;
var ImplicitBool = true;
var ImplicitString = "Time, marches on...";

// Print out the underlying type.
Console.WriteLine("myInt is a: {0}", ImplicitInt.GetType().Name);
Console.WriteLine("myBool is a: {0}", ImplicitBool.GetType().Name);
Console.WriteLine("myString is a: {0}", ImplicitString.GetType().Name);

}


Implicitly type conversion can be used also with arrays, generics and custom types.

static void ImplicitVars()
{

// More implicitly typed local variables.
var evenNumbers = new int[] { 2, 4, 6, 8 };
var myMinivans = new List();
var myCar = new SportsCar();

Console.WriteLine("evenNumbers is a: {0}", evenNumbers.GetType().Name);
Console.WriteLine("myMinivans is a: {0}", myMinivans.GetType().Name);
Console.WriteLine("myCar is a: {0}", myCar.GetType().Name);
}


You can also use the "var" inside for loops like below...

static void VarInForeachLoop()
{

var oddNumbers = new int[] { 1, 3, 5, 7 };

// Use "var" in a standard foreach loop.

foreach (var item in oddNumbers)
{
Console.WriteLine("Item value: {0}", item);
}

// Use a strongly typed System.Int32 to iterate over contents.
foreach (int item in oddNumbers) // it also works fine.
{
Console.WriteLine("Item value: {0}", item);
}
}

Limitations in Implicitly Typed Variables:

1) You can not use "var" as return values, parameter of method or field of any type. "Var” can be used inside method or roperty scope only.

class NeverCompile
{

// Error! var cannot be used as field data!
private var ImplicitInt = 100;

// Error! var cannot be used as a return value
// or parameter type!
public var ImplicitMethod(var p, var q){}
}

2) Variable defined using "var" must assigned initial value at the time of declaration and it should be null.

// Error! Must assign a value!
var ImplicitData;

// Error! Must assign value at exact time of declaration!
var ImplicitInt;
ImplicitInt= 0;

// Error! Can't assign null as initial value!
var refrenceType = null;

However it is possible to assign value null once it is recognized as reference type as below.

// OK, is fruit is a reference type!
var fruit = new Apple();
fruit = null;

However it is possible to assign value of implicit var to another varible either implicit or typed.

// Also OK!
var myInt = 0;
var anotherInt = myInt;
string myString = "Wake up!";
var myData = myString;

Following code also work fine.
static int ReturnVar()
{
var retVal = 999;
return retVal;

}

3) Nullable Implicit Type local is not possible.
var? notposible = null;//Error
var? i =0;//Error

Implicitly Typed variable is strogly typed variable.

Once value is assigned to the variable defined using var you can not change it's value which represents the different datatype. Means it is not same as used in VB using var or used in the scripting laguage like VBScript or javaScript. see the below code.

static void ImplicitTypingIsStrongTyping()
{

// The compiler knows "s" is a System.String.

var s = "This variable can only hold string data!";

s = "This works no error at all!...";

// Can invoke any member of the underlying type.
string upper = s.ToUpper();

// Error! Can't assign numerical data to a a string!
s = 44;

// Error! Can't perform this operation with string!
s = "Tejas" + 44;
}


When to User "var" ?

Generally if you know that variable will hold integer value then there is no need to declare it as var. you can declare it as int datatype but var token can be used with the LINQ query largely because output of the LINQ query can be vary on the based of the select statement when query so it is the best way to use var in the LINQ query.

Note: var is Contextual Keyword of C#. You can declare variable like int var =0 compiler will not give any error, but when it is used as var i=0 then complier treats "var" as contextual keyword.

What do you mean by Contextual Keyword?
A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. The following contextual keywords are introduced in this section:

get Defines an accessor method for a property or an indexer.
partial Defines partial classes, structs, and interfaces throughout the same compilation unit.
set Defines an accessor method for a property or an indexer.
where Adds constraints to a generic declaration.
yield Used in an iterator block to return a value to the enumerator object or to signal the end of iteration.
value Used to set accessors and to add or remove event handlers.

All query keywords introduced in C# 3.0 are also contextual. See Query Keywords (C# Reference).

See Also
Concepts

C# Reference
C# Programming Guide
C# Keywords

No comments: