C# C# Basics C# Syntax Types

When declaring a variable without giving it a value, why don't we use the 'var' keyword before typing in the type?

This confuses me so I apologise if it's a dumb question but why don't we have to use 'var' before 'int' when declaring a variable?

1 Answer

Steven Parker
Steven Parker
203,731 Points

Both "var" and "int" declare a variable, but they would never both be used in the same declaration.

"Var" can only be used when you also initialize it because the compiler examines the value being assigned to determine what type of variable to create. On the other hand, "int" declares the type explicitly, so it can be used with or without initialization.

Hi Steven, So let me see if my analogy works here (and if I'm understanding the concept too!) -

If I point to an object in the real world and say, "Hey Steven can you bring me that thing?" Although technically correct, it's not very specific, much like var. So var is roughly equivalent to the English word thing. If I said, "Hey Steven can you bring me that orange?" You now know what type of thing I'm talking about & makes it easier for you to fulfill my request...or in C# : str thing = orange .

So just as it would be weird to say: "Hey Steven can you bring me that thing orange?", we don't want to say var str thing = orange.