Var. This C# keyword references a type in an implicit way. It aliases any type. The aliased type is determined by the C# compiler, and has no performance penalty.
The var keyword is an example of syntactic sugar. It makes programs shorter and easier to read. It can be used in method bodies and loops.
Example. Let us look at some C# code examples of the var keyword. To begin, here is a code example that shows the var keyword referencing a List of ints.
Info This code uses the var keyword and the List type. The variable is known to be a List. So var refers to a List of ints.
using System;
using System.Collections.Generic;
// Hover over the var keyword.// ... Visual Studio will tell us the referenced type.
var codes = new List<int> { 1, 2, 7, 9 };
Console.WriteLine("LIST COUNT: " + codes.Count);LIST COUNT: 4
Query expression example. Next we see a query expression. It returns an IEnumerable of ints. The query is evaluated to this type—and var implicitly refers to that type.
Tip 2 The var keyword can represent any type that can be determined at compile-time. It is precisely equivalent after compilation.
using System;
using System.Linq;
int[] numbers = { 1, 2, 3, 4, 5 };
// Use a query expression to get all the odd numbers from the array.// ... The var stores the result IEnumerable.
var items = from item in numbers
where (item % 2 == 1)
select item;
// Each item is an int.
foreach (var item in items)
{
Console.WriteLine("VAR LOOP: {0}", item);
}
// Use the same loop but without var.
foreach (int item in items)
{
Console.WriteLine("LOOP 2: {0}", item);
}VAR LOOP: 1
VAR LOOP: 3
VAR LOOP: 5
LOOP 2: 1
LOOP 2: 3
LOOP 2: 5
Error, null var. We cannot assign a var to null. This will result in a compiler warning. We also can not use var as a parameter type or a return value of a method.
class Program
{
static void Main()
{
var test = null;
}
}Error CS0815
Cannot assign <null> to an implicitly-typed variable
Dictionary. Var simplifies the syntax of generic types. It is particularly useful for generic collections such as Dictionary. It allows you to omit the long type parameter lists.
And This simplifies the syntax of your code. It improves readability. Use it in your code.
using System;
using System.Collections.Generic;
// Use implicit type keyword var on Dictionary instance.// ... Then use the collection itself.
var data = new Dictionary<string, int>();
data.Add("cat", 2);
data.Add("dog", 1);
Console.WriteLine("cat - dog = {0}", data["cat"] - data["dog"]);cat - dog = 1
Case var. We can use the var keyword to capture variables when matching in a switch statement. Usually this is used when dealing with tuples and other complex types.
Here We match the two items in the tuple in each case statement. We use var before specifying the temporary variable names.
Info We can name the variable names "size" and "color" anything we want, or even omit the names with an underscore.
using System;
var bird = (20, "blue");
// Use var to capture variables in case statements.
switch (bird)
{
case var (size, color) when size >= 10:
Console.WriteLine($"SIZE >= 10, {color}");
break;
case var (_, color):
Console.WriteLine($"SIZE < 10, {color}");
break;
}SIZE >= 10, blue
Summary. Var is for implicit typing. It can make code easier to read. A variable that uses the "var" type has the same type as one that has its type specified directly.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2024 (new example).