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#

What is considered best practice? Using var or using string, double, etcetc.

I find that declaring the types makes the code more readable, however, what is more commonplace in the industry? Would it hinder my progress to be more strict?

3 Answers

I hear from a lot of developers they prefer var over explicit typing for several reasons

  • It looks cleaner and is more readable than longly named types
  • It you can easily identify variable declaration from other stuff right away
  • It looks like in most other programming languages ( this is a big point for full-stack developers )
  • ...

Explicit typing has it advantages too:

  • you directly see the type that variable is supposed to store
  • you can directly jump to the type definitions in most IDEs
  • declaration are possible

In open source libraries and code contributions I read more explicit typing than implicit via var or const, mainly because of the advantage of look ups you make to the type definitions (big libraries (like AspNetCore) often contain half a dozen types)

Steven Parker
Steven Parker
231,108 Points

I can't speak for the whole industry, but I generally use "var" whenever the type is obvious, such as when initializing from literals. But if there's any doubt what the variable will be used for, an explicit type is a good idea.

Thanks both for your help.