Friday, October 24, 2008

[C#] "var" ... Implicitly Typed Variables - When to use?

Alrighty, so during a code review it was brought to my attention that as of C# 3.0 programmers can now use implicit declaration of variables, which was completely contrary to my previous understanding of the language - in that I thought it was solely strongly typed much like C/C++. That is not the case.
Explicit Declaration: int myCount;
Implicit Declaration: var myCount;
Implicit declarations rely on the compiler to chose the best type for you. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

Now while I can see this being handy for many reasons [from what I've read LINQ requires this type of functionality - but I haven't used LINQ yet]... it also troubles me - mostly due to readibility issues if overused. I've done some quick searches and I am not alone in my concerns. I'm just figured I'd list here when *I* think that the use of var can and should be applied for inferring a type.

*** Implicit Usage [My Thoughts] ***
Case 1: If it's required.
Duh... such as with LINQ examples... sometimes you just can't get around it ^^

Case 2: If you are dealing with a very, very, very long type name.
Example:
OhHaiThisIsMyLongClassName myLongClass;
Would become:
var myLongClass;

Case 3: If you Initialize the object on the same line.
Canvas myObj = new Canvas();
Would become:
var myObj = new Canvas(); // <-- We know in the same line what this variable's type is.

Now granted... if the name of your variable does not indicate what it is actually representing, then perhaps there is a programming issue with the naming convention used. I've seen this as an arguement in favor of using "var" - it forces descriptive naming conventions which would in the end actually increase the readibility of a programming.

Really in the end I believe it comes down to personal style - but it's good to keep in mind the pros and cons of using both explicit/implicit typing of variables.


MSDN Documentation on Implicit Typed Variables
Another discussion about when to use "var"

.

1 comment:

Jack said...

I like var, it implicit at compile time and will not hurt performance.