Possible Duplicate:
C# 'var' vs specific type performance
Hi all,
I recently saw code that uses var
a lot.
E.g.:
var myString = GetAnyString();
var myInstance = GetClass();
instead of
string myString = GetAnyString();
MyClass myInstance = GetClass();
Besides the readability (I think that using var
is not very readable), are there any advantages and/or drawbacks using it? How about performance
As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable. Do not use var.
var is on ES6 for legacy reasons. In theory, the let statement is better since it behaves more predictably on block scopes, but it won't work with more outdated interpreters. So, if you're coding with only ES6 in mind, go for let.
In Javascript, it doesn't matter how many times you use the keyword “var”. If it's the same name in the same function, you are pointing to the same variable. This function scope can be a source of a lot of bugs.
Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.
It is subjective, but I don't like using vars. As for me they don't improve readability.
But general guideline on var
usage is following:
Use var
when it is absolutely clear what type of the variable is being declared:
Dictionary<string, Dictionary<string, string>> varOfSomeLongType = new Dictionary<string, Dictionary<string, string>>();
or when you are declaring variable of anonymous type:
var linqResult = from element in SomeCollection
select new { element.A, element.B }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With