After some thought I’ve come up with two simple rules to go by when using implicitly typed variables to make sure that you don’t end up seeing their nasty, code obfuscating side. But I’m getting ahead of myself, first the important question that someone is bound to not be asking right about now:
What are Implicit Types?
// Explicit List<string> userNames = new List<string>(); // Implicit var userNames = new List<string>();
Implicit types in C# are basically placeholder types that the compiler figures out for you. They may hold any type to begin with, but once they are assigned a value of a certain type, that type is noted by the compiler and will error if you try to assign a different type later.
// Okay! quote is being assigned a string value var quote = "Things that try to look like things often do look more like things than things."; // Compile Error! Cannot convert source type 'float' to target type 'string' quote = 4.0f;
When are Implicit Types Bad?
The use of implicit types becomes a problem when a type cannot be determined without access to external or non-local bits of code. Here’s an example of what I mean; are you able to tell me what type will be printed to the console below assuming that the elem is valid?
// Allow the compiler to determine the type var elem = _listOfElements[idx]; // What type will be printed here? Console.WriteLine(elem.GetType());
When are Implicit Types Useful?
The thing I’ve found implicit types most useful for is saving keystrokes and making refactoring large swaths of code easier. Consider the following example to illustrate why this can be useful. It is notable that if you’re the compiler, these statements end up being exactly the same.
// Explicit Dictionary<string, Luggage> thisDict = new Dictionary<string, Luggage>(); // Implicit var thatDict = new Dictionary<string, Luggage>();
Not only does the implicitly typed variable take fewer keystrokes to type out initially, but if you have to change the type of the variable at a later point you only need to change it once, rather than changing it on both sides. The real impact here is time saved when changing tens or hundreds of occurrences of complex type variables like this across many files.
Two Rules.
I mentioned at the top that I had come up with two rules for making sure that you get all the upsides and none of the downsides of implicit typing, so here they are:
1. Only use implicit typing when the type can be readily determined by looking at the local context surrounding the line.
2. Never use implicit types on numbers.
By following these two simple rules, you’ll reduce the number of keystrokes you have to type, as well as maintain the ability to determine the type correctly without Intellisense (e.g. Code snippets in a webpage.)