Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var: a Type or a keyword

MSDN categorizes var under Types.

variables that are declared at method scope can have an implicit type var

what does 'implicit type var' mean in this context?

Strictly said, if I have it to explain to fellow programmers.

Can I say; var is a Type, or do I have to say; var is a keyword that instructs the compiler to determine the type itself.

note: this is not meant to start a discussion about var, nor to learn the use of var. For once and for all I want to know excactly how to describe it and msdn is a bit confusing, that's it.

like image 484
Caspar Kleijne Avatar asked Sep 11 '10 07:09

Caspar Kleijne


1 Answers

var is a contextual keyword - along with yield, add and get for example.

In other words, you can use it as an identifer without prefixing it with @, but it still has a special meaning to the compiler in some places (i.e. where a type name is expected for a local variable declaration).

Using var to declare a local variable asks the compiler to infer the type of the variable based on the expression on the right hand side. For example:

var list = new List<string>();
var anon = new { Foo = "bar" };

The type of list is List<string>; the type of anon is an anonymous type, also introduced in C# 3. Part of the reason for introducing var in C# 3 was to allow for strongly typed variables using anonymous types - the variable still has the appropriate compile-time type, even though you couldn't explicitly state that type.

There are a few cases where var doesn't work, however, if the compiler doesn't have enough information:

var cantUseNull = null;
var cantUseLambda = x => x.Length;

There are others too. In each case you could just cast the expression on the right-hand side, so that the compiler knew what to use - but in that case you might as well just declare the variable explicitly instead.

<plug>
You can read more about this in C# in Depth. Fortunately, the chapter covering this is still available for free from the first edition page (you want chapter 8). I can't remember how much I've changed this chapter in the second edition...
</plug>

like image 103
Jon Skeet Avatar answered Oct 16 '22 18:10

Jon Skeet