What Is Var Data Type in C#?


Larry Thompson

What Is Var Data Type in C#?

In C#, the var keyword is used to declare a variable without explicitly specifying its data type. This allows the compiler to determine the type of the variable based on the value assigned to it. The var keyword was introduced in C# 3.0 as part of the language’s support for implicit typing.

When you use the var keyword, you let the compiler infer the type of a variable based on its initialization expression. This means that you don’t have to explicitly write out the data type, making your code more concise and easier to read.

Let’s take a look at an example to understand how var works:

    var name = "John Doe";
    var age = 30;
    var isEmployed = true;

In this example, we have declared three variables: name, age, and isEmployed. We didn’t specify their data types explicitly using keywords like string, int, or bool. Instead, we used the var keyword, allowing the compiler to infer their types based on their respective initialization expressions.

The compiler determines that the variable name has a data type of string, because it was initialized with a string literal. Similarly, it determines that both age and isEmployed