Implicitly Typed Local Variables

Earlier we saw a new feature “Automatic Properties” in C# 3.0. Today we are going to see the use of new ‘var’ keyword.

C# 3.0 allows local variables in methods to have an implicit type by identifying it from the type of its initial value. For instance,

var str = “Adil“; // str is compiled as a string

var col = new[] { 0, 1, 2 }; // col is compiled as int[]

var anoType= new { Name = “Terry“, Age = 34 }; //anonymous type

When you call the GetType method on str, it will return System.String type.

A point of consideration is that var keyword is not like var in javascript and it does not mean that variable is late-bound. It is actually a keyword for compiler to determine and assign the type with respect to the value initialized.

Also note that var keyword cannot be used in class variables and also in passing variables to method or returning from method. It does not support nullable type as well. Further you need to give it some value at the time of declaring otherwise it will be an error. Let say,

var someVar;  someVar= 1; // not allowed

The var keyword does not impress until it is used with LINQ. We will see it’s use with LINQ in some later post.

  • var anoType= new { Name = “Terry”, Age = 34 }; //anonymous type

    What this Line of Code means ?

    What are Anonymous Types ??

  • What is the difference between a Framework and a Library ??

  • Hi Fahad,
    I appreciate your interest. This LoC means that you are creating an anonymous type having two properties Name and Age.
    Anonymous type allows you to encapsulate read only fields in an object without explicitly defining the object in your code.
    Anonymous type are useful when using with query of LINQ. They are also reference type and derive from object.
    Hope that gives you a better picture.

    Adil

  • What is the difference between a Framework and a Library ??

    Hey, I didn’t write something like this in my blog? 🙂 Any ways Its good to see your interest in clearing up things.

    Framework is a general term, It is integration of different units that combine to provide functionality.

    So we tune your question as what is the difference between .NET Framework and a Library?

    And just as I said you can think of this like Library is a unit of Framework. In particular, .NET Framework combines different units such as Class Library and Common Language Runtime to provide desired functionality.

    Does this make sense to you? 🙂 I hope so. Feel free to discuss further.

  • Very good information about local variables…