I hope i am syntactically clear with my heading, but for those who find this title to be bewildered, my heading is “Implicitly typed local variables in C# 3.0”. We will dive a little into this. I take the heading and try to demystify why papa of this feature named this so!
Implicit => Then it means something that is done explicitly in previous versions is going to be done implicitly.
Typed => That “something” in the previous statement is about “TYPES”. So combining this definitions i get the following “The user doesn’t need to explicitly mention types in statements, instead types will be inferred from the usage by the compiler”. i love csc.exe
Local Variable => That types should only be scoped local. So refining our previous definition i get this, “The user doesn’t need to explicitly mention types in statements, instead types will be inferred from the usage by the compiler, provided the scope of the type is a local”.
The var keyword is introduced in C# 3.0 to allow users to use this feature. The MSDN article is self sufficient to provide necessary info about this. We will discuss something that i found interesting.
i) Is the VARIANT keyword in Visual Basic and the var keyword described here synonymous?
- They are synonymous in definition, as both infer the type from the usage. But the type resolving happens at compile time in case of C# and in runtime in Visual basic. So we can say that the var keyword is type safe.
- For VARIANT in Visual basic because the type is resolved at runtime, the variant can be in the same scope hold different types as shown in the example below. So this is absolutely valid.
- In case of C#, a similar program will generate error “Cannot implicitly convert type 'string' to 'int' “. since during compilation itself, the var is replaced by int and thence the succeeding statement of assigning a string to an int fails. Don’t play with Big Bro…………
If you look at the compilation of the statement then you will see something like this. The var will be compiled and transformed as int in corresponding IL. This is done to ensure type safety and to avoid some nasty runtime crashes that is a bottleneck with VARIANT in visual basic while using with COM components. :)
Lot of other interesting stuff like, why var cannot be a member variable or cannot be a part of method signature, why they should be initialized during declaration itself are discussed in the MSDN article itself. Hope you had a good time.