When should 'var' be used in C# | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

When should 'var' be used in C#

In which situation is it a good idea to use var myvariable (rather than declare the variable with a strong type)?

15th Jan 2017, 9:46 PM
ifl
ifl - avatar
2 Answers
+ 8
I've seen it used most often when working with objects or Windows forms. It's best used when there's no uncertainty of what data type var will convert to. With objects, you always see the name of the class you're working with. Ex: var obj = new myClass() will always be of type myClass, so the var is guaranteed to be that type. With forms, you can receive inputs like yes/no button clicks, dropdown box selections, etc., and the data types for those inputs are long and usually complicated. It works as a shorthand for those names. Ex: var input = MessageBoxButton.Retry is always a message box input.
15th Jan 2017, 11:46 PM
Tamra
Tamra - avatar
- 1
When I see variables usually it is dealing with numbers such as making a player movement script or some type of game number system.
16th Jan 2017, 9:09 PM
Hectic Airman
Hectic Airman - avatar