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
- Local Variable Type Inference with var
- When to Avoid var
- The dynamic Type
- Target-Typed new Expressions