Partilhar via


C# 3.0 : Useful keyword “var”

People complain about the keyword “var”. Especially, when we use it with the strict programming language like C# in .NET. Developers also complain about the readability part of it. I totally agree with them, but the scenarios where there will be no options but the “var” when it comes to on the fly projection of Language INtegrated Query (LINQ). Can you initialize Anonymous Type without “var”? There are so many no-nos. Let’s appreciate it and start use. I already have explained in one of my previous blogs,

Scenario 1 (Anonymous Type)

+++++++++++++++++++

When you have no type defined but want to create that, we need “var”.

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

You cannot assume the name created by compiler for this Anonymous Type. Please feel free to add comment to my blog if you have choice to add type in the above example while declaring the variable.

Scenario 2 (Projecting it to IEnumerable<AnonymousType>)

++++++++++++++++++++++++++++++++++++++

Suppose if you want to get the output containing only the selected column you have to project it to a type.

IEnumerable<CustomerSelect> query =

from c in db.Customers

where c.City == "London"

select new CustomerSelect

{

CustID = c.CustomerID,

CompanyName = c.CompanyName

};

As you cannot have “,” as you are used to for any T-SQL query. Here you need everything as strongly typed. So you need to create a class, here I have created one,

class CustomerSelect

{

public int CustID { get; set; }

public string CompanyName { get; set; }

}

So here boldly you can retrieve the result like, IEnumerable<CustomerSelect>

in case if you do not want to use var here. But if you are lazy developer like me then you might not be interested in creating class for every need. Rather you will use anonymous type and get the IEnumerable<AnounymousType> as query output. But how will be defining IEnumerable of some anonymous type (in fact no type). No wander you must appreciate the real power of “var” here.

var query =

from c in db.Customers

where c.City == "London"

select new

{

CustID = c.CustomerID,

CompanyName = c.CompanyName

};

Namoskar!!!

Comments

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

  • Anonymous
    December 18, 2007
    Why not dim? Why not keep such a cosmetic choice have parity with VB?

  • Anonymous
    December 18, 2007
    People who complain about "var" with statically typed programming languages usually don't understand what they're talking about :). They're just too used to thinking in C and can't understand that they get the same protection while letting the compiler infer the types for them. Using var lets you focus on your actual algorithms rather than have to wade through more type annotations. How is: List<int> ints = new List<int>(); superior to: var ints = new List<int>(); What about when you have things like Dictionary<int, Expression<Func<int,bool>>> -- you really want to type that twice? The biggest downside to var is that it's limited to locals.

  • Anonymous
    December 18, 2007
    @Mike Var can also be shared accross the methods, http://blogs.msdn.com/wriju/archive/2007/12/19/sharing-var-across-the-method.aspx Wriju

  • Anonymous
    December 18, 2007
    Well sure, since everything's an object. But that sorta defeats the purpose of having a statically typed system :)

  • Anonymous
    April 28, 2009
    @Mike - You're confusing Anonymous Types and the var keyword.  These are not the same thing.  Anonymous Types are limited to locals, but declaring static types with the var keyword is no different than any other declaration and is not limited to locals. To that end, I think you're wrong in your defense of var being used to define static types.  When it's defining a local, then I would say it's harmless.  When it's defining a variable to a function result, it's very difficult to read.  Look at this code for instance: private static ICollection<ValidationError> ValidateProperties(object o) {                            if (!ValidatorConfiguration.Rules.ContainsKey(o.GetType()))    {        return null;    }    var errors = new List<ValidationError>(10);    foreach (var property in ValidatorConfiguration.Rules[o.GetType()].Properties)    {        var value = property.Property.GetValue(o, null);        foreach (var validator in property.Validators)        {            if (validator.IsValid(o, value)) { continue; }            errors.Add(new ValidationError(property.Property.Name));            break;        }    }    return errors; } var is used to define method results and it's very difficult to read.