Partager via


C# 3.0: Vote for the keyword “var”

You all probably know what is “var”. You might have a question why this new keyword is required in programming language like C#. One of the few strong reasons is to have an Anonymous Type stored in a variable. Whenever you have to initialize a type you have to mention the type before you give a name for a variable. But can you do something like this,

 

AnonymousType~1 obj = new {Id = 1, Name="Wriju"};

The anonymous type will be decided during compile time and it is random. You simple cannot assume anything here. The proper way of declaration would be,

var obj = new {Id = 1, Name="Wriju"};

 

Another area in LINQ where to get multi column output we often use anonymous type and get the IEnumerable of that type. So when you have no type in place can you declare IEnumerable of that type?

 

var q = from c in db.Customers

        select new { c.CompanyName, c.ContactName };

If you want to have IEnumerable<T> then you have to have type T defined in your apps somewhere. But it is very inconvenient to have a type defined every time you want to get a different combination.

 

Things to remember,

Ø var cannot be used as public property/field

Ø var cannot be a return type of any method

 

Otherwise var rocks and it is Reflection enabled. Performance is equal.

 

Namoskar!!!

Comments

  • Anonymous
    November 05, 2007
    Welcome to the thirty-fifth edition of Community Convergence. This week we have an interview with C#

  • Anonymous
    November 18, 2007
    Is not c# getting too Large? like c++ ? and now you add "var"?

  • Anonymous
    December 14, 2007
    With this exciting release of .NET Framework 3.5 I have been exploring its magic and sharing the finding

  • Anonymous
    December 17, 2007
    People complain about the keyword “var”. Especially, when we use it with the strict programming language