Introduction
Starting from Visual C# 3.0 onwards, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.
I would like to sum up the above statement as follows: The var keyword is a shorthand way of allowing the compiler to infer the type for you - to save your fingers some work.
Background
C# 3.0 now provide us a new keyword named var, which one can use in place of specifying a formal data type (such a int, float, string or bool). When we use var keyword, the compiler will automatically to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.
Some things need to be made quite clear:
- Using var doesn't make your variables "weakly typed". All variables declared as var are strongly typed.
- var isn't a type. The actual type is figured out at compile-time.
- Due to the fact that the actual types are resolved at compile-time, the var keyword cannot be "slower".
Using the code
Basic understanding of var keyword
Suppose there is a method which states how to declare explicit variables.
void DeclaringExplicitVariables()
{
int testInt = 0;
float testFloat = 0.0f;
string testString = “writing code”;
bool testBool = false;
}
Now we will write the above method in such a way that it’s variable
are declared as Implicit variables.
void DeclaringImplicitVariables()
{
var testInt = 0;
var testFloat = 0.0f;
var testString = "writing code";
var testBool = false;
}
We can also determine the type of variable the Implicit variables get assigned to after initialization using reflection as follows:-
void GetTypeofImplicitVariables()
{
var testInt = 0;
var testFloat = 0.0f;
var testString = "writing code";
var testBool = false;
var wholeNumbers = new int[] {0,1,2,3};
var testStringList = new List<String>();
Console.WriteLine("type of testInt is : {0}", testInt.GetType().Name);
Console.WriteLine("type of testFloat is : {0}", testFloat.GetType().Name);
Console.WriteLine("type of testString is : {0}", testString.GetType().Name);
Console.WriteLine("type of testBool is : {0}", testBool.GetType().Name);
Console.WriteLine("type of wholeNumbers is : {0}", wholeNumbers.GetType().Name);
Console.WriteLine("type of testStringList is : {0}", testStringList.GetType().Name);
Console.ReadLine();
}
Output of the above program will be :-
type of testInt is : Int32
type of testFloat is : Single
type of testString is : String
type of testBool is : Boolean
type of wholeNumbers is : Int32[]
type of testStringList is : List’1
Var variables can be used in looping through foreach loop. As expected, the compiler infers the correct type by itself.
void VarUsageInForEachLoop()
{
var wholeNumbers = new int[] {0,1,2,3};
foreach(var item in wholeNumbers)
{
Console.WriteLine("Item value : {0}", item);
}
}
Do’s & Don’ts while using Implicit Variables
1. It can only be used as local variables in a method or property scope. It is illegal to use them as field type, return value or parameters.
class ErrorClass
{
private var testInt = 0;
public var ErrorMethod(var first, var second)
{
var sum = fisrt+second;
return sum;
}
}
2. Implicit variables must be assigned an initial value at the exact time of declaration and can’t be assigned to null.
var testInt;
var testInt;
testing = 0;
var testObj = null;
3. It is absolutely correct to assign a null value to an implicit variable after its initialization to a refrence type.
var humanBeing = new LivingBeing();
humanBeing = null;
4. It is absolutely correct to assign the value of an implicit type local variable to the value of other variables.
var testInt = 0;
var secondInt = testInt;
float testFloat = 0.0f;
var secondFloat = testFloat;
5. Implicit variables can be used to send value to the calling method in case of where the method return type is the same type as that of the defined var variable.
string ReturnString()
{
var retVariable = "hello world";
return retVariable;
}
6. Directly declaring a nullable type implicit variable is not permissible.
var? testInt = 0;
var? testFloat = 0.0f;
7. While declaring a implicit type array it should be kept in mind that they are of same type (i.e all int, or all string, but not mixture of them)
var intArray = new[] {2,5,8,12};
var mixArray = new[]{1, “hello”, 2, “world”};
Points of Interest
I hope after reading this article might have given you a clear picture about the var variable in C# and you will enjoy using it up in your day to day code frequently.
Wishing you all might enjoy reading this article, as much as I enjoyed writing it out.