To var or not to var

Do you think it’s better to use var keyword of C# when you declare variables, or always set them up using their types?

I personally prefer the var shortcut but only when the name of the variable identifies its type, especially if there is a constructor for that type called or when a cast is used to convert an expression value to a specific type. This way I think the code remains readable enough. And if one really needs the type of the variable can hover the variable name and Visual Studio should be able to offer the information.

Update: A few colleagues told me (and after more thinking I find they are right) that the code is less readable with var declarations, even if the type can be inferred from the variable name. It is simply a matter of easily recognizing types in front of variable names, but also you can right click the type name in Visual Studo if it is there and go to declaration or implementation, so it’s more useful to not var than to var. Of course, using var remains useful for anonymous types such as when you split Linq expressions in multiple statements.


About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in .NET, C# and tagged , , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s