Exploring Implicitly Typed Variables in C#

When learning C#, one of the convenient features I discovered is implicitly typed variables. Using the var
keyword, you can let the compiler infer the type of a variable based on the value you assign. This can make your code cleaner and easier to read.
What Are Implicitly Typed Variables?
Implicitly typed variables are declared using the var
keyword:
var myFavoriteWoman = "Wife"; // inferred as string
var myFavoriteNumber = 13; // inferred as int
var herFavoriteNumber = 7; // inferred as int
Here, the compiler automatically determines the data type:
"Wife"
→string
13
→int
7
→int
Important:
var
is not a dynamic type. The type is fixed at compile time, and you cannot later assign a value of a different type.
Using Implicitly Typed Variables in Calculations
You can use these variables in expressions just like explicitly typed ones:
int ourNumbersTogether = myFavoriteNumber + herFavoriteNumber;
var ourNumbersTogetherVar = myFavoriteNumber + herFavoriteNumber; // inferred as int
Console.WriteLine(ourNumbersTogetherVar); // Output: 20
Console.WriteLine(ourNumbersTogether); // Output: 20
Both ourNumbersTogether
and ourNumbersTogetherVar
hold the same value, but the second one demonstrates how var
can simplify your code by letting the compiler handle type inference.
What I Learned
Cleaner Code –
var
reduces the need to explicitly write long type names.Type Safety – Even though
var
infers the type, it’s still strongly typed; the type cannot change after assignment.Readability – When used correctly,
var
makes code more readable, especially for complex types like collections or LINQ queries.
Subscribe to my newsletter
Read articles from Kelvin R. Tobias directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
