Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using var or not using var [duplicate]

Tags:

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

like image 241
Simon Linder Avatar asked Oct 29 '10 09:10

Simon Linder


People also ask

Should I use VAR or not?

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.

Should you still use VAR in ES6?

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.

Why we should not use VAR in JavaScript?

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.

Is it necessary to use VAR in JavaScript?

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.


1 Answers

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 }
like image 144
Andrew Bezzub Avatar answered Sep 22 '22 14:09

Andrew Bezzub