5 March 2014

var datatype in C#


The var keyword can be used in place of a type when declaring a variable to allow the compiler to infer the type of the variable. This feature can be used to shorten variable declarations, especially when instantiating generic types, and is even necessary with LINQ expressions (since queries may generate very complex types).
The following:
int num = 123;
string str = "asdf";
Dictionary<int, string> dict = new Dictionary<int, string>();
is equivalent to:
var num = 123;
var str = "asdf";
var dict = new Dictionary<int, string>();
var does not create a "variant" type; the type is simply inferred by the compiler. In situations where the type cannot be inferred, the compiler generates an error:
var str; // no assignment, can't infer type
 
void Function(var arg1, var arg2) // can't infer type
{
    ...
}


 

var Type: 
  • C# 3.0 adds the interesting behavior of Declaring Local Variables Implicitly. This means that there is no need to mention the data type when declaring a variable. A local variable can be declared implicitly using the var keyword in C#.
  • Declaring local variables implicitly has some restrictions; the variable must be initialized to some expression that can not be null. 

    var a= 10; 
    var z = "Rekha";
  • The primary reason for its existence is the introduction of anonymous types in C#
  • Another point to stress is that variable inference does not work for class level fields or method arguments or anywhere else other than for local variables in a method.
Advantages :
  • Less typing with no loss of functionality
  • Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
  • Makes it so you don't have to write the same name twice in a variable declaration.
  • Some features, such as declaring a strongly typed anonymous type local variable, require the use of var

No comments:

Post a Comment