0Pricing
C# Academy · Lesson

When to Avoid var

Keep code readable by typing explicitly when needed.

var Can Hide the Type

var is convenient, but it can obscure what a variable actually is, hurting readability for the next reader.

using System;

class Program {
    static void Main() {
        var x = Compute();
        Console.WriteLine(x);
    }
    static int Compute() { return 42; }
}

Unclear Method Returns

When a method name does not reveal the return type, prefer an explicit type so readers know what they have.

using System;

class Program {
    static double Process() { return 3.14; }
    static void Main() {
        double value = Process();
        Console.WriteLine(value);
    }
}

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