+ 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)?
2 Réponses
+ 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.
- 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.