What's the point of the var keyword?
Update: There are two related questions here, actually:
1. Why do I have to declare variables at all?
2. What use is "var" in a language that makes you declare variables?
The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:
As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:
SomeGeneric<VeryLongTypename<NestedTypename>> thing = new
SomeGeneric<VeryLongTypename<NestedTypename>>();
Verbose and error-prone, right? So now they let you do this:
var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();
By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.
What is the purpose of the var keyword and when should I use it (or omit it)?
If you're in the global scope then there's not much difference. Read Kangax's answer for explanation
If you're in a function then var
will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it):
// These are both globals
var foo = 1;
bar = 2;
function()
{
var foo = 1; // Local
bar = 2; // Global
// Execute an anonymous function
(function()
{
var wibble = 1; // Local
foo = 2; // Inherits from scope above (creating a closure)
moo = 3; // Global
}())
}
If you're not doing an assignment then you need to use var
:
var x; // Declare x
What is the purpose of 'var'?
Anonymous Types was the big one, but also reducing repetition within methods:
Dictionary<MyCustomType, List<MyOtherCustomType>> dict = new Dictionary<MyCustomType, List<MyOtherCustomType>>();
What advantages does using var have over the explicit type in C#?
The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists. All other uses I consider to be lazy coding.
What is the equivalent of the C# 'var' keyword in Java?
There is none. Alas, you have to type out the full type name.
Edit: 7 years after being posted, type inference for local variables (with var
) was added in Java 10.
Edit: 6 years after being posted, to collect some of the comments from below:
The reason C# has the
var
keyword is because it's possible to have Types that have no name in .NET. Eg:var myData = new { a = 1, b = "2" };
In this case, it would be impossible to give a proper type to
myData
. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.var
is not the same asdynamic
.var
iables are still 100% statically typed. This will not compile:var myString = "foo";
myString = 3;var
is also useful when the type is obvious from context. For example:var currentUser = User.GetCurrent();
I can say that in any code that I am responsible for,
currentUser
has aUser
or derived class in it. Obviously, if your implementation ofUser.GetCurrent
return an int, then maybe this is a detriment to you.This has nothing to do with
var
, but if you have weird inheritance hierarchies where you shadow methods with other methods (egnew public void DoAThing()
), don't forget that non-virtual methods are affected by the Type they are cast as.I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:
class Foo {
public void Non() {}
public virtual void Virt() {}
}
class Bar : Foo {
public new void Non() {}
public override void Virt() {}
}
class Baz {
public static Foo GetFoo() {
return new Bar();
}
}
var foo = Baz.GetFoo();
foo.Non(); // <- Foo.Non, not Bar.Non
foo.Virt(); // <- Bar.Virt
var bar = (Bar)foo;
bar.Non(); // <- Bar.Non, not Foo.Non
bar.Virt(); // <- Still Bar.VirtAs indicated, virtual methods are not affected by this.
No, there is no non-clumsy way to initialize a
var
without an actual variable.var foo1 = "bar"; //good
var foo2; //bad, what type?
var foo3 = null; //bad, null doesn't have a type
var foo4 = default(var); //what?
var foo5 = (object)null; //legal, but go home, you're drunkIn this case, just do it the old fashioned way:
object foo6;
C# var keyword usage
I think it's fine to use var
where it makes the code easier to read, which for me would mean that the type that var
is replacing must be completely obvious.
For example, this would be a good use of var
(contrived example):
var thing = new Dictionary<int, KeyValuePair<string, int>>();
However this would be a bad use of var
:
var thing = GetThingFromDatabase();
What is the difference between var and string in C#?
The keyword var
is used for declaration of implicit types. If you are using a named type for the variable, there is no other difference than readability (and opinions differ on which is better). Example:
var s = "asdf";
gives exactly the same result as:
string s = "asdf";
However, if you have an unnamed type, you have to use var
to declare a variable that has that type. Example:
var o = new { s = "asdf" };
There is no corresponding declaration using a named type, because the type of the object that is created doesn't have a name.
The var
keyword is often used with LINQ and LINQ extension methods, when the result doesn't have a named type. Example:
var result = someList.Where(x => x.Age < 10).Select(x => new { name = x.Name });
Related Topics
Deserializing JSON When Sometimes Array and Sometimes Object
Differencebetween File.Readlines() and File.Readalllines()
Embedding Unmanaged Dll into a Managed C# Dll
How to Get a Property Value Based on the Name
Stop Visual Studio Debug Putting Slash in String Containing Double Quotes
How to Use Linq Contains(String[]) Instead of Contains(String)
Combining N Datatables into a Single Datatable
How to Get Difference Between Two Dates in Year/Month/Week/Day
How to Seed a Random Class to Avoid Getting Duplicate Random Values
How to Set a Property Value with Reflection
C# Open a New Form Then Close the Current Form
Searching for a Specific Jtoken by Name in a Jobject Hierarchy
Shorter Syntax for Casting from a List<X> to a List<Y>