Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Adam McGrade
Adam McGrade
26,333 Points

Conventions for declaring variables in C#

I am currently learning C# and I have noticed that in some code variables are declared explicitly with a type provided, and in other pieces of code, variables are declared with the var keyword.

I was wondering if this is something that is a preference of the author or if there is a best practice way to declare variables that most C# programmers follow?

Thanks

1 Answer

Steven Parker
Steven Parker
231,122 Points

I'm not sure there's universal agreement on this one. Personally, I think "var" is fine where the actual type is reasonably obvious to someone reading the code based on what's on the right side of the assignment. Otherwise, declaring the type explicitly is worthwhile just for the improvement in readability, even if the compiler can figure it out.