8
Jun/100
Jun/100
Implicit Types (var) in C#
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;
