Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#

Basic Understanding of Implicit Variables in C# 3.0

Rate me:
Please Sign up or sign in to vote.
3.19/5 (12 votes)
13 Apr 2012CPOL3 min read 22.2K   9   5
This article gives you a brief introduction to Implicit Variable provided by .net Framework 3.0 onwards and illustrating its usage.

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()
{
	// datatype variablename = intialvalue;
	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 variablename = intialvalue;
	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
{
	//Error as implicit variables can’t be used as field type
	private var testInt = 0;

	// Error as var can neither be used as parameter nor as return type
	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.

//Error as it must be assigned a value
var testInt;

//Error as value must be assigned at exact time of declaration 
var testInt;
testing = 0;

//Error as it can’t be initialize to null
var testObj = null; 

3.    It is absolutely correct to assign a null value to an implicit variable after its initialization to a refrence type.

// It’s correct only if LivingBeing is reference 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.

//Error as implicit variables can’t be of nullable type
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)

//Correct as all data are of integer type.
var intArray = new[] {2,5,8,12};

//Error as data are of mixed type
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) 1E
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionMy 5, but just for completeness Pin
Daniele Rota Nodari16-Apr-12 1:44
Daniele Rota Nodari16-Apr-12 1:44 
SuggestionYour Article Lacks Depth and Accuracy PinPopular
AspDotNetDev13-Apr-12 21:34
protectorAspDotNetDev13-Apr-12 21:34 
GeneralRe: Your Article Lacks Depth and Accuracy Pin
dave.dolan14-Apr-12 16:25
dave.dolan14-Apr-12 16:25 
GeneralMy vote of 5 Pin
Member 78722083-Jul-11 9:14
Member 78722083-Jul-11 9:14 
GeneralRe: My vote of 5 Pin
pawankalakoti6-Jul-11 9:13
pawankalakoti6-Jul-11 9:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.