The myth of misusage of the var keyword since C# 3.0

Microsoft .NET

C# 3.0 introduced a new keyword, var. The var keyword allows you to utilize type inference at compile time which is a really cool feature. Here’s an extremely basic example.

var message = "Hello World";

This should be self-explanatory: The compiler will resolve the local variable ‘message’ to be of type ‘string’, which is inferred by the value in the assignment statement. This is pretty cool, but it was never meant to change the C# specification or rid of using strongly typed names. The optimal usage of the var keyword is when you are dealing with Anonymous Types, and Generics. It was actually introduced along with the release of Linq in C# 3.0 which deals with these two language features quite often.

There are other scenarios where var is useful though, take this statement:

List<KeyValuePair<AccountRoles[], ToolStripMenuItem>> m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

That is a pretty knarly declaration and assignment statement, and this is a scenario where the var keyword would actually be recommended to improve readability to:

var m_GuardedMenuItems = new List<KeyValuePair<AccountRoles[], ToolStripMenuItem>>();

This also benefits the language outside the scope of the compiler. You can easily see that the first sample causes the syntax highlighter on this page to have to scroll – so for programming books, reference material, and blogs like this var has its use outside the realm of actual C# programs.

Bad: When the type is not obvious.

var doc = Factory.GetDocument(); // What is doc?

Good: When the type is obvious.

var text = new StringBuilder(); // We easily can see it is inferred to StringBuilder

The truth is, you can come up with more good examples of when to use var, then when not to use it. Another example would be refactoring. Say you have the following.

List<Order> orders = Factory.GetOrders();

Later down the road if the return type of Factory.GetOrders() were to change, you would have to go refactor every declaration that uses that method. However with var, you would not have had to done this if you used var in the first place.

var is pretty controversial, but the general consensus from the experts is its not as bad as everyone thinks.

Leave a Comment

Your email address will not be published. Required fields are marked *