var Keyword
This page was last reviewed on Apr 27, 2023.
Dot Net Perls
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.
First 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.
int, uint
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);
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 You can use var with the foreach-loop. You can use it like any other variable.
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); }
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
Implementation. Here we see the internal implementation and behavior of C# code that uses the var keyword. There are two int32 values in the IL.
Note The int declaration is the same as the var declaration in the IL. So the execution engine does not know that you used var.
And They are compiled to the same IL. The var keyword is equally fast as explicit types like int or string.
Intermediate Language
public int ReturnValue() { var a = 5; int b = 5; return a + b; }
.method public hidebysig instance int32 ReturnValue() cil managed { // Code size 9 (0x9) .maxstack 1 .locals init ([0] int32 result, [1] int32 CS$1$0000) IL_0000: nop IL_0001: ldc.i4.5 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: br.s IL_0007 IL_0007: ldloc.1 IL_0008: ret } // end of method VarKW::ReturnValue
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
Type systems. The C# language has a strong type system. Memory is labeled by what kind of object it contains. The language uses strong types to enforce code quality.
So The C# compiler raises errors and warnings because it wants your code to work properly.
And It makes inferences about your code and can deduce the type of a variable.
Thus Languages sometimes have lengthy keywords. You can reduce this with var—it's only 3 letters.
Uses. One tip is to use var on generic types. The Dictionary type has verbose syntax—it uses a lot of brackets and letters and a comma.
Info Some code becomes much easier to read with this keyword. Var can even make code refactoring easier.
Tip If you change a type name with refactoring, a var type local will not need to be changed.
Var is for implicit typing. We find out what it stands for by hovering over it in Visual Studio. We use var for brevity—it makes code easier to understand.
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 Apr 27, 2023 (edit).
© 2007-2024 Sam Allen.