CSharp - var Implicitly Typed Local Variables

Introduction

When you declare and initialize a variable in one step, if the compiler can infer the type from the initialization expression, you can use the keyword var in place of the type.

For example:

var x = "book2s.com";
var y = new System.Text.StringBuilder();
var z = (float)Math.PI;

This is equivalent to:

string x = "book2s.com";
System.Text.StringBuilder y = new System.Text.StringBuilder();
float z = (float)Math.PI;

Implicitly typed variables are statically typed.

The following generates a compile-time error:

var x = 5;
x = "hello";    // Compile-time error; x is of type int