C#3.0Features. Select(feature => feature.Name == “Implicitly typed local variables”)

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.
    •    1: Imports System
         2: FooProcedure()
         3:     Dim i as Variant
         4:     i = 100
         5:     i = "Boo and Doo went to Zoo"
         6: 'This is perfectly valid.
         7: End FooProcedure
    • 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…………
    •    1: static void Main(string []args)
         2: {
         3:     var myData = 44;
         4:     myData = "Boo and Doo Went to Zoo"
         5: }

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. :)

image      =>image 

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.