Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
220,415 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.