#803 – Situations When You Might Use the var Keyword

The var keyword allows you to avoid entering the full type of a variable, letting the compiler infer the type.  The variable is still strongly-typed, i.e. the type is known at compile time.

There is debate about when you should use var.  It’s use ends up dictated by coding style guidelines or personal preference.

You must use var when dealing with anonymous types because the compiler generates only an internal type name.

var myDog = new { Name = "Kirby", Age = 14 };

You might  use var when using LINQ, when the exact type of the query result is not apparent.

            var someDogs = from aDog in dogs
                          where aDog.Age > 10
                          select aDog.Name + "(" + aDog.Nickname + ")";

You might also use var to avoid having to repeat a type name that is already present in an expression.

            var dogs = new List<Dog>();
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: