C# var

Summary: in this tutorial, you’ll learn to use the C# var keyword to declare implicit-typed variables.

Introduction to the C# var keyword

Starting from C# 3, you can use the var keyword to declare implicit-typed variables.

For example, the following declares a variable and initializes its value as a literal string:

string message = "Hi";Code language: C# (cs)

In this example, we use the string type for the message variable at the beginning of the declaration and a literal string as the initial value. The message is an explicit-typed variable.

However, from the value "Hi", the compiler can infer the variable as string. Therefore, the explicit type at the beginning of the declaration is redundant.

To avoid this redundancy, you can use the var keyword in place of the explicit type at the beginning of the variable declaration like this:

var message = "Hi";Code language: C# (cs)

In this example, the message is an implicit-typed variable.

The var keyword does not signal a special kind of variable. It’s syntactic shorthand for any type that the compiler can infer from the initialization of a variable declaration.

In the above example, the var is the shorthand for the string type.

Once the compiler can infer the variable type, it’s fixed and unchangeable. For example, you cannot assign an integer to the message variable like this:

var message = "Hi";
message = 100; // errorCode language: C# (cs)

C# only allows you to use the var keyword with a variable that includes an initialization. The following will result in an error:

var amount;Code language: C# (cs)

Error:

Implicitly typed variables must be initializedCode language: C# (cs)

Summary

  • Use the var keyword for a variable with initialization from which the compiler can infer a type.
  • Variables, which are declared with the var keyword, are implicit-typed variables.
Was this tutorial helpful ?