Day 14: var keyword Do’s and Don’ts

Leslie Ramírez
2 min readDec 23, 2021

--

Hello there 👋👋 It’s our 14th coding winter day. For today let’s talk about some of the cool things we can do with var keyword.

Let’s go!

On a daily basis, we declare and initialize a variable in one step. Beginning with C# 3, variables that are declared at method scope can be var. what is the difference between implicitly and explicitly typed variables?

An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type that’s the only difference. We can use as follow:

The use of var is really useful when we are not sure the value of that variable It’s going to hold. A common use of the var keyword is with constructor invocation expressions. There are cases when we can use var:

Do’s

  • Use must use the var keyword to reference an anonymous type because it doesn’t have a name.
  • It will actually increase type safety in your code by alerting you to implicit casts. The best example in the foreach statement
  • Make sure to use a clear naming for your var types.
  • Use var when the type of the declaration is obvious from the initializer, especially if it is object creation. This eliminates redundancy.

Don’ts

  • Don’t use var when the return type isn’t obvious

· Don’t use var when the method returns a concrete type.

Conclusions

Remember whenever you decide to use an implicitly typed variable or not you have to be sure your code readability is the best.

If you want to learn more about it follow this link:

If you enjoyed this article, please hold down the clap button 👏👏👏 Don’t forget to follow our Coding winter Calendar. Have a wonderful day! 🧡 💛 💚🧡 💛 💚

--

--

Leslie Ramírez

I am Microsoft MVP in the award category: Developers technologies, a professional with several years in software development specifically in .NET technology.