Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use var instead of a type? [duplicate]

Possible Duplicate:
ReSharper and var

After I have installed ReSharper it demands(by warnings) that I use var whenever possible, for example

UnhandledExceptionEventArgs ue = (UnhandledExceptionEventArgs) t; 

ReSharper wants to turn it into

var ue = (UnhandledExceptionEventArgs) t; 

I like the first version better, is there any reason to prefer var? better performance? anything? or is it just a code style?

like image 436
IAdapter Avatar asked Feb 01 '11 22:02

IAdapter


People also ask

Why should you use VAR?

var requires less typing. It also is shorter and easier to read, for instance, than Dictionary<int,IList> . var requires less code changes if the return type of a method call changes. You only have to change the method declaration, not every place it's used.

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.

What is the advantage of using var in C#?

The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists.

When should I use VAR in Java?

In Java, var can be used only where type inference is desired; it cannot be used where a type is declared explicitly. If val were added, it too could be used only where type inference is used. The use of var or val in Java could not be used to control immutability if the type were declared explicitly.


1 Answers

It's really just a coding style. The compiler generates the exact same for both variants.

See also here for the performance question:

  • Will using 'var' affect performance?
like image 186
Martin Buberl Avatar answered Oct 23 '22 21:10

Martin Buberl