Saturday, December 10, 2011

Implicitly Typed Local Variables (var keyword)

You can use implicitly typed local variables whenever you want the compiler to determine the type of a local variable.
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

The below examples show different ways in which local variables can be declared with var:

// i is compiled as an int
var i = 5;

// s is compiled as a string
var s = "Hello";

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

// expr is compiled as IEnumerable
// or perhaps IQueryable
var expr = from c in customers where c.City == "London" select c;

// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };

// list is compiled as List
var list = new List();

The var keyword may be used in the following cases as well:

* On local variables (variables declared at method scope) as shown in the previous example.

* In a for initialization statement.

for(var x = 1; x < 10; x++)

* In a foreach initialization statement.

foreach(var item in list){...}

* In a using statement.

using (var file = new StreamReader("C:\\myfile.txt")) {...}

Enjoy the programming! :)

5 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.


    java training in bangalore

    ReplyDelete

  3. Hi there, just became alert to your blog through Google, and found that it's really informative. I'm going to watch out for brussels. I will appreciate if you continue this in future. Numerous people will be benefited from your writing. Cheers! sign in to gmail

    ReplyDelete

  4. Hats off to your presence of mind..I really enjoyed reading your blog. I really appreciate your information which you shared with us.

    web designing course in chennai

    ReplyDelete