Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Var Examples

This C# article provides examples for the var keyword. Var is an implicit type that aliases the actual type.

Var is an implicit type.

It aliases any type. The aliased type is determined by the C# compiler. This has no performance penalty. Var is excellent (and tasty) syntactic sugar. It makes programs shorter and easier to read.

Example. First we look at some examples of the var keyword. Here is a code example of the var keyword being used in three contexts. Please note that you need a recent version of the .NET Framework to compile this program.

Based on:

.NET 4.5

C# program that uses var keyword

using System;
using System.Collections.Generic;
using System.Linq;

class Program
    public static void Main()
	// 1.
	// var is always available, not just in Linq.
	var cat = new List<int>
	// Hover over the 'var' keyword and Visual Studio
	// will tell you what it really is.

	// 2.
	// This example display odd numbers.
	// Returns IEnumerable<T> (where T is int).
	var items = from item in cat
		    where (item % 2 == 1)
		    select item;

	// 3.
	// Each item is an int.
	foreach (var item in items)
	// The previous loop is the same as this:
	foreach (int item in items)




This code uses the var keyword and the List type. The variable is known to be a List. You can hover over the var keyword and Visual Studio tells you the type List. This feature is called IntelliSense.

Visual Studio

Next, we see the var items query. It returns IEnumerable<int>. The query expression is evaluated to this type—and var implicitly refers to that type. You can use var with the foreach-loop. You can use it like any other variable.


Tip: The var keyword can represent any type that can be determined at compile-time. It is precisely equivalent after compilation.

Type systems. The C# language has a strong type system. This means that memory is labeled by what kind of object it contains. The language uses strong types to enforce code quality. Variables are both memory and also type annotations.

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.

Compile-Time Error

Brevity: Languages sometimes have lengthy keywords. You can reduce this with var—it's only three letters.

Limitations. Next, we consider some interesting limitations of the var keyword. You can't assign a var to null. This will result in the CS0825 warning. You also can't use var as a parameter type or a return value of a method.


Implementation. Next, we look at the internal implementation and behavior of the var keyword. C# code is turned into IL. You can see it with a utility called IL Disassembler provided with Visual Studio. There are two int32 values in the IL below.

IL Disassembler

Note: The int declaration is the same as the var declaration in the IL. So the execution engine doesn't 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.


Method using var: C#

public int ReturnValue()
    var a = 5;
    int b = 5;

    return a + b;

IL of the method

.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

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. 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.

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. This simplifies the syntax of your code. It improves readability.

C# program that uses var, Dictionary

using System;
using System.Collections.Generic;

class Program
    static void Main()
	// 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

Var is a handy keyword. We find out what it stands for by hovering over it in Visual Studio. It has similarities to #define or typedef in C++. We use var for brevity. It makes the code easier to understand.

Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf