0Pricing
C# Academy · Lesson

Local Variable Type Inference with var

Use var where the type is obvious.

What is var?

var lets the compiler infer a local variable type from the initializer. The variable is still strongly typed at compile time.

using System;

class Program {
    static void Main() {
        var count = 10;
        Console.WriteLine(count);
    }
}

var Is Not dynamic

var is resolved at compile time. var x = 10 is exactly an int and cannot later hold a string.

using System;

class Program {
    static void Main() {
        var name = "Ada";
        Console.WriteLine(name.GetType().Name);
    }
}

All lessons in this course

  1. Local Variable Type Inference with var
  2. When to Avoid var
  3. The dynamic Type
  4. Target-Typed new Expressions
← Back to C# Academy