Brian's Blog

items I see across my tribes

var -- Using Implicitly Typed locals

February 27
by briancarter 27. February 2010 11:49

I’ve been using the beta of ReSharper 5 as an initial peer review.  The tool offers good advice on ways to improve your code.  I also like to see the “green” light in the upper right corner :-)

With version 4, some people are complaining about numerous suggestions to convert explicit type to "var" keyword.

image

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.  As shown above, the complier knows the type because of the information provided on the right hand side. 

It is important to understand that the var keyword does not mean “variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

I’ve been trying to keep my solutions DRY (Don't Repeat Yourself).  Using var allows me to keep the DRY principal and invoke var usage wherever possible.  This style allows me to do a code read much quicker:

using (var fileStream = new FileStream(

There are many sides to this discussion, for me, it removes code noise.  It reduces the amount of text I need to read, or rather skip.  I don’t need to specify the type twice – which really helps when using generics. 

Of course, you can hide this suggestion in ReSharper by using Options / Code Inspection / Inspection Severity, or by using Alt-Enter and selecting "Change severity" option.

Thank You for listening.

Categories: Development

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading




 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.