
You want to see how the implicit type keyword var can be used on a generic type such as the Dictionary type. The var keyword is particularly useful for generic collections such as Dictionary because it allows you to omit the long type parameter lists. This simplifies the syntax of your code, improving readability.

Let's look at an example in the C# language that provides a functional demonstration of the code. Instead of specifying a "Dictionary<string, int> data = new Dictionary<string, int>()", we can omit the first type, changing the left side to "var data". The C# compiler can then automatically infer the exact type from the right side of the assignment expression. There is no change in the instructions generated.
This C# program uses the var keyword on a Dictionary instance. Var simplifies syntax.
Program that uses var Dictionary syntax [C#]
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"]);
}
}
Output
cat - dog = 1
Is this syntactic sugar? Yes, the var keyword here is a form of syntactic sugar—it serves only to change the representation of the program text at a high level. The C# compiler will literally use logic to derive the type of the variable for you. Therefore, the low-level instructions generated in intermediate language will not differ, and performance and type-safety are unaffected. In this example, the Dictionary could easily be changed to a List or Tuple type.

We explored the implicit keyword feature in the C# language when applied to generic types such as the Dictionary type. While changing the type "int" to "var" has little syntactic benefit, changing the type "Dictionary<string, int>" to "var" improves readability in some contexts. Further, the var keyword only affects the highest level of your program representation, and the low-level instructions generated are identical to more verbose representations.
Var Examples Collections