Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual C#
C# Reference
C# Keywords
 var
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Language Reference
var (C# Reference)

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

For more information, see Implicitly Typed Local Variables (C# Programming Guide) and Type Relationships in LINQ Query Operations (C#).

The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable<string>. However, in the second expression, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

C#
// Example #1: var is optional because
// the select clause specifies a string
string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

// Because each element in the sequence is a string, 
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    Console.WriteLine(s);
}

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Once assigned, type will not change automatically      LyalinDotCom ... AnnaDault   |   Edit   |   Show History

The following code will fail with an error on the second line:

var MyVar = 500;
MyVar = "Change To String"; // This line fails with message: "Cannot convert INT to STRING"

Other languages that have types similar to C#'s implementation dont have this restriction.

Tags What's this?: Add a tag
Flag as ContentBug
Var is a Compile-Time Construct      jopincar   |   Edit   |   Show History
You are misunderstanding how var works. Var just means the compiler will infer the type for you. It doesn't mean that the compile-time type of a variable can change over time. No statically typed language allows the same variable to be both a string and an int. If you wanted to do what you have listed above, why not use object or two different variables?
This is not a bug.      ejkitchen   |   Edit   |   Show History

This whole thread should be deleted as it is clear the original poster does not understand the concept of this new feature. This is not a restriction but indeed a very good design.

Tags What's this?: Add a tag
Flag as ContentBug
Question is good      ESTAN   |   Edit   |   Show History
Hi,
I don't think this thread should be deleted. As far as I can see he didn't understand the concept, so he stated that. I can ensure you that it helped me out understanding the concept of var, and with his statement it helped me even more. So thank you LyalinDotCom for showing us how it doesn't work, and thanks jopincar for telling us why it doesn't work. And sure that LyalinDotCom now gets the idea about the var keyword.
Tags What's this?: Add a tag
Flag as ContentBug
Consolidation of comments      Thomas Lee   |   Edit   |   Show History
Perhaps we could create a single consolidated post describing the issue and explaining it (and remove the other posts?
Tags What's this?: Add a tag
Flag as ContentBug
var is not variant      Anil Mujagic   |   Edit   |   Show History
The var keyword does NOT represent some kind of "variant" data type, but is here to represent a variable that will get it's data type from the result data type of the expression used to initialize it during creation.
Tags What's this?: Add a tag
Flag as ContentBug
shall we "var" with select only.      Aman Shaikh   |   Edit   |   Show History
Well the concept of "var" is a bit clear to me, but what about its boundaries and limitations.
Tags What's this?: Add a tag
Flag as ContentBug
'var' can slow down test-driven development      Manfred Lange   |   Edit   |   Show History
I think the whole post should stay. It's valuable for all readers to see how other people look at 'var' as a language feature and what problems they encounter.

As I just learned 'var' can slow down tests-driven development (TDD) in some cases. This can happen when you write assertions against a 'var' but the value of the 'var' is assigned the return value of a method that is not yet implemented.

For more details please see http://manfredlange.blogspot.com/2009/03/implicit-typing-can-make-tdd-harder.html
Tags What's this?: tdd (x) Add a tag
Flag as ContentBug
'var' adds readability      wesmcclure   |   Edit   |   Show History
I think it is very important to point out that this construct can radically improve the readability of code, especially test code where readability is of primary importance. It also helps reduce the verbosity of generic declarations that are often duplicated in the instantiation. The best part is it forces us to think a bit more about the variable name and put more intention there rather than leaving it hidden in the type.
Tags What's this?: Add a tag
Flag as ContentBug
'var' does not add readability.      Jmelgaard   |   Edit   |   Show History
wesmcclure >>

How in the world does 'var' add readability to you?

first of go to this link and check the folowing statement at the bottom: (http://msdn.microsoft.com/en-us/library/bb384061.aspx)

"However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required."

It is funny that is the exact opposite opinion.

And now, explain to me how this is more readable to you:

public void DoStuff(IMemberProvider memberProvider)
{ var members = memberProvider.RetreiveMembers();
Console.WriteLine(members.ToString());
  ... Do more stuff with members.
}

See what I did there?... you have absolutely NO clue what so ever to as what members is, could be a list, could be some sort of repository, could be an array...
All we do know, is that it is most likely something that contains members.
(unless you have the entire project AND uses an IDE... suddenly code becomes much more painfull to read since you need to interact with your IDE to understand it)...

I can at all time except the "var" keyword if its used as:

public void DoStuff(IMemberProvider memberProvider)
{ var members = new List<IMember>();
  memberProvider.AddMembers(members);
... Do more stuff.
}
In the above you suddenly know for sure what 'members' is, does it improve readability?... I wouldn't say so, but maybe that is because I read from Left to right...
(like most people reading English)...

or maybe you prefere naming conventions as:

public void DoStuff(IMemberProvider memberProvider)
{ var listOfIMemberMembers = memberProvider.RetreiveMembers();
Console.WriteLine(listOfIMemberMembers.ToString());
  ... Do more stuff with listOfIMemberMembers.

  var listOfIMemberAdmins = memberProvider.RetreiveAdministrators();
Console.WriteLine(listOfIMemberAdmins .ToString());
  ... Do more stuff with listOfIMemberAdmins.
}

Having to embed the type in the name is something at least I learned a long time ago that I didn't like. In the above we even have some ugly redundancy
for the first few lines ('listOfMember' describes the type, 'Members' descripe the content).

I will at ANY time prefer the following dumb of code, and I will ALWAYS claim that is more readable that any of the above...:

public void DoStuff(IMemberProvider memberProvider)
{ List<IMember> members = memberProvider.RetreiveMembers();
Console.WriteLine(members.ToString());
  ... Do more stuff with members.

  List<IMember> admins = memberProvider.RetreiveAdministrators();
Console.WriteLine(members.ToString());
  ... Do more stuff with members.
}

(Also keep in mind 'var' was introduced BECAUSE it was needed for anonumous types)



Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker