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.
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.
- // int value
- var age = 25;
- Console.WriteLine("var holds an int = {0}", age);
- // string value
- var name = "Mahesh Chand";
- 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.
- // array value
- var odds = new[] { 1, 3, 5, 7, 9 };
- Console.WriteLine("var holds an array of numbers");
- foreach (var num in odds)
- {
- Console.WriteLine("{0}", num);
- }
“var” in a for statement
A var keyword can be used in a for statement.
- for (var x = 1; x < 10; x++)
- {
- Console.WriteLine(x);
- }
“var” in a foreach statement
A var keyword can be used in a foreach statement. The following code example uses a foreach statement.
- // array value
- var odds = new[] { 1, 3, 5, 7, 9 };
- Console.WriteLine("var holds an array of numbers");
- foreach (var num in odds)
- {
- Console.WriteLine("{0}", num);
- }
“var” in a using statement
A var keyword can be used in a using statement. See the following code example:
- using (var file = new System.IO.StreamReader(@"C:\Temp\Mahesh.txt"))
- {
- string line;
- while ((line = file.ReadLine()) != null)
- {
- Console.WriteLine(line);
- }
- }
“var” in anonymous Types
The “var” is used to store anonymous types. The code snippet in creates and stores an anonymous type.
- // author is an anonymous type
- var author = new { Name = "Mahesh Chand", Book = "Programming C# 7.0", Year = 2017, Price = 45.95 };
- Console.WriteLine("var holds an anonymous type");
- Console.WriteLine("Author details: {0}, {1}, {2}, {3}", author.Name, author.Book, author.Year, author.Price);
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:
- string[] authors = { "Mahesh", "Mike", "Allen", "David", "Monica" };
- var authorQ = from author in authors
- where author[0] == 'M'
- select author;
- foreach (var a in authorQ)
- {
- Console.WriteLine(a);
- }
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.
- var aQuery = from auth in Authors
- select new { auth.Name };
- foreach (var a in aQuery)
- {
- Console.WriteLine(a.Name);
- }
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.
Summary
In this article, you saw several use cases of a var variable in C#.