var-Implicitly Typed Local Variables - CSharp Language Basics

CSharp examples for Language Basics:var

Introduction

If the compiler can infer the type from the initialization expression, you can use the keyword var in place of the type declaration.

For example:

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

This is precisely equivalent to:

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

Because of this direct equivalence, implicitly typed variables are statically typed.

For example, the following generates a compile-time error:

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

Related Tutorials