What Does “var” Mean In C#?

The “var” keyword is used to declare a var type variable in C#. In this article, you will learn how to use a var in C#.

What Does “var” Mean In C#?

 
C# is a strongly typed language which means, you must declare a variable type before you can use it. But what if you don’t know the type of the variable? C# lets you declare local variables without giving them explicit types. It is possible with the help of the “var” type variable.
 
The “var” keyword is used to declare a var type variable. The var type variable can be used to store a simple .NET data type, a complex type, an anonymous type, or a user-defined type.
 
var in csharp 
 
Before I start talking about when to use and when not to use a var variable, let’s look at some use cases of the var variable.
 

The “var” local variables

 
The following code example uses a var to store an int value, a string value, and an array of numbers. 
  1. // int value  
  2. var age = 25;  
  3. Console.WriteLine("var holds an int = {0}", age);  
  4. // string value  
  5. var name = "Mahesh Chand";  
  6. Console.WriteLine("var holds a string = {0}"name);  
The following code example creates an array of numbers and stores it in a var. A var is also used to loop through the array items. 
  1. // array value  
  2. var odds = new[] { 1, 3, 5, 7, 9 };  
  3. Console.WriteLine("var holds an array of numbers");  
  4. foreach (var num in odds)  
  5. {  
  6. Console.WriteLine("{0}", num);  
  7. }  

“var” in a for statement

 
A var keyword can be used in a for statement. 
  1. for (var x = 1; x < 10; x++)  
  2. {  
  3. Console.WriteLine(x);  
  4. }  

“var” in a foreach statement

 
A var keyword can be used in a foreach statement. The following code example uses a foreach statement. 
  1. // array value  
  2. var odds = new[] { 1, 3, 5, 7, 9 };  
  3. Console.WriteLine("var holds an array of numbers");  
  4. foreach (var num in odds)  
  5. {  
  6. Console.WriteLine("{0}", num);  
  7. }  

“var” in a using statement

 
A var keyword can be used in a using statement. See the following code example: 
  1. using (var file = new System.IO.StreamReader(@"C:\Temp\Mahesh.txt"))  
  2. {  
  3. string line;  
  4. while ((line = file.ReadLine()) != null)  
  5. {  
  6. Console.WriteLine(line);  
  7. }  
  8. }  

“var” in anonymous Types

 
The “var” is used to store anonymous types. The code snippet in creates and stores an anonymous type. 
  1. // author is an anonymous type  
  2. var author = new { Name = "Mahesh Chand", Book = "Programming C# 7.0"Year = 2017, Price = 45.95 };  
  3. Console.WriteLine("var holds an anonymous type");  
  4. Console.WriteLine("Author details: {0}, {1}, {2}, {3}", author.Name, author.Book, author.Year, author.Price);  
Learn more about anonymous types here: Anonymous Types In C#.
 

Restrictions on implicit type variables

 
The following restrictions apply to implicitly-typed variable declarations: 
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, r to a method group,or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression.
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as a part of an implicitly typed local variable declaration.
 

When to use var

 
  • Use of “var” is not recommended everywhere. The var was created to handle declarations when the type is not known, such as generic types, lambdas, and query expressions. If you already know the type of a variable, you must declare that explicitly. Remember, if you don’t declare a variable explicitly, the compiler must do extra work to determine the type. While the cost of this operation may not be significant, it’s just unnecessary burden on the compiler.
  • Don’t use var for simple local variable types that are known to you.
  • Here are some of the common uses of the var keyword.
  • Use of var when you’re not sure what type of data will be stored in a variable.
  • Use in anonymous types and anonymous collections.
  • Use of var improves code readability. Use when class names are extremely long.
  • Imported unmanaged code types that doesn’t follow naming conventions.
 

Var in Query Expressions

 
The var is often used in LINQ queries. Let’s look at this code example: 
  1. string[] authors = { "Mahesh""Mike""Allen""David""Monica" };  
  2. var authorQ = from author in authors  
  3. where author[0] == 'M'  
  4. select author;  
  5. foreach (var a in authorQ)  
  6. {  
  7. Console.WriteLine(a);  
  8. }  
In the above code sample, the use of the “var” is optional, because the type of the query return is an array of strings. The use of var in the foreach loop is also optional, because we know the item is a string.
 
Here is another example where the result is a collection of anonymous type. 
  1. var aQuery = from auth in Authors  
  2. select new { auth.Name };  
  3. foreach (var a in aQuery)  
  4. {  
  5. Console.WriteLine(a.Name);  
  6. }  
In this above code, use of a var makes sense. Use of a var eliminates the need of creating a new class for the result. The foreach loop also uses a var type to read anonymous types.
 
Recommended reading: The var Keyword in C#.
 

Summary

 
In this article, you saw several use cases of a var variable in C#.