Reputation: 21
var data type take more time to compile (i.e convert in to IL ) so why we need var datatype as well as compliler know the particular dattype at runtime(i.e Compile time only) so when am using this may program may have chance to reduce the performance.
any one explain this concept with example and compile time duration please.....
Upvotes: 2
Views: 298
Reputation: 54724
The purpose of the var
keyword is to let you declare variables of anonymous types. For instance, I can rewrite a var
declaration for plain types:
// This:
var i = 6;
// ...is the same as this:
int i = 6;
However I can't do the same thing for compiler-generated types:
// This isn't valid C#:
var a = new { i = 6, s = "hello" };
(what goes here?) a = new { i = 6, s = "hello" };
Upvotes: 2
Reputation: 1499880
var
isn't a data type - it's just a way of telling the compiler to infer the type itself. If doesn't make any difference at execution time. The compiled code will be exactly the same.
var
was primarily introduced as part of anonymous types where you can't explicitly declare a variable of the appropriate type, as it has no name. This feature in turn is primarily used in LINQ, where you often have ad-hoc projections.
There are other benefits of var
however in terms of reducing duplication - for example, if you're already specifying the type exactly in the assignment expression, there's little point in having it on the left-hand side:
// Simple
var namesMap = new Dictionary<string, Person>();
// Duplication and more to read
Dictionary<string, Person> namesMap = new Dictionary<string, Person>();
Upvotes: 5