So what are "implicit" and "Explicit" typed variables and what are the differences between them? To better understand something it is always good to know the terminology and what it means you can get a full picture of the topic.
- Explicit: stated clearly and in detail, leaving no room for confusion or doubt.
- Implicit: implied though not plainly expressed.
How they Apply
So how do these terms apply to programming and why does it really matter? Well, in programming, the simplest way to explain this topic is when you declare your variable type (string, int, bool, etc) you can specifically say what it is, explicit, or vaguely state what it is, implicit. One of the bigger impacts this takes on your code is the readability of it. Here’s some examples:
List<int> lstIntegers = new List<int>();
var lstIntegers = new List<int>();
In both cases the coding is correct and easily read. The instantiation clearly lets the person know you are creating a new list of integers. In cases such as these or other types like Dictionary<key, value>, this makes your line a lot shorter and easier to read and is the perfect time to use implicit variable types.
When to Use
My question when I was first started to learn coding and C# was, “if you can use implicit in every case why or when would you not want to?” Well that again comes down to readability. Look at the example below:
List<MyContactObjects> lstObjects = GetContractContactInfo();
var lstObjects = GetContractContactInfo();
In these cases, it is no longer clear between the two what you are working with unless you dive into the custom method GetContractContactInfo(); to find out what it returns. Now this is not a big deal, but it still makes it more work on someone who is not familiar with the code to have to read through and is not as clearly stated. Whereas the first one you can clearly tell the method will return a list of your custom object.
Although there is a readability difference, sometimes there really is no impact on performance between using the two types. The differences with the performance of this is how the system boxes and unboxes those types which becomes a topic all its own. Whether large scale or small scale though it still does not have a noticeable impact.
Why Think of It?
All of this is important information to keep in mind because when it comes to code if there is one thing I have learned it is that a person should always keep in mind that they aren’t the one who will probably maintain it. In such cases you want to make things as easy as possible, while still strong and effective, for the person who might have to maintain it after you. With implicit variable types it is easy to just slap a var in there and go on your way but it may not always be the best solution. Too commonly people will over use this and make the code harder to read than it needs to be. So always try to be courteous and keep others in mind.