C# var keyword

I’m working my way through the C# 3.0 Language Enhancements videos on LearnVisualStudio.Net.  (Note:  LearnVisualStudio has many videos that are available for free from the MSDN website, but I think that you need a paid subscription to view this series.)  When I’m studying new programming concepts, I find that hearing someone talk about it helps me get it into my head in a way that reading alone doesn’t do.  I really want to learn LINQ, but it turns out that you don’t just jump into it.  Rather, you need to learn some key building blocks first.  So, today I studied the C# var keyword.

Var is just a shortcut you can use to create a variable without actually figuring out what type it is.  Instead, the compiler figures out the type for you, based on what you are assigning the variable to.

For example:

var a = 3;

is equivalent to

int a = 3;

When would you want to use var?  Infrequently, if you subscribe to the “keep your code as obvious as possible” theory.

One possible use is when you are instantiating an object using “new”.  You could argue that typing:

var b = new List<string>();

is as clear and less verbose than:

List<string> b = new List<string>();

But the real use is when you are using LINQ and it’s pretty unclear – and maybe you don’t even care  – what the actual type is.  For instance, do you know what type is returned by the following LINQ query?

string[] names = { “Turtle”,”Toad”,”Frog”,”Lizard” };
var cc = from n in names where n.StartsWith(“T”) select n;

I thought cc would be of type string[], but it is actually:


Right.  Var is looking pretty good right now, isn’t it?

The object.GetType method is useful to find out what type you actually have.  For instance:

int a = 3;
if(a.GetType() == typeof(int))
    // whatever

There you have it.  The next video in the series is “Object and Collection Initializers”.  That doesn’t sound too glamorous, but we’ll see.



Post a Comment

Required fields are marked *

%d bloggers like this: