Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 'var' keyword versus explicitly defined variables [duplicate]

I'm currently using ReSharper's 30-day trial, and so far I've been impressed with the suggestions it makes. One suggestion puzzles me, however.

When I explicitly define a variable, such as:

List<String> lstString = new List<String>(); 

ReSharped adds a little squiggly green line and tells me to:

Use implicitly type local variable declaration.

If I then follow its suggestion, ReSharper changes the line of code to:

var lstString = new List<String>(); 

So, is there some sort of performance gain to be had from changing the List<String> to a var, or is this merely a peculiarity of ReSharper? I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal.

like image 547
JustinT Avatar asked Jan 09 '09 19:01

JustinT


1 Answers

So, is there some sort of performance gain to be had from changing the List to a var

No but this is not the only valid reason for a refactoring. More importantly, it removes redundance and makes the code shorter without any loss in clarity.

I've always been taught that explicitly defining a variable, rather than using a dynamic, is more optimal.

You misunderstand what var means. This is not in any way dynamic, since it produces the same output. It just means that the compiler figures the type for the variable out by itself. It's obviously capable of doing so, since this is the same mechanism used to test for type safety and correctness.

It also removes a completely useless code duplication. For simple types, this might not be much. But consider:

SomeNamespace.AndSomeVeryLongTypeName foo = new SomeNamespace.AndSomeVeryLongTypeName(); 

Clearly, in this case doubling the name is not just unnecessary but actually harmful.

like image 90
Konrad Rudolph Avatar answered Sep 22 '22 08:09

Konrad Rudolph