+ 1

Can you use "var" in everything?

It may be bad practice, but I would like to know as I'm new. Is there any reason why I shouldn't use "var" for everything? Does it use more processing power as it needs to identify each variable?

29th Aug 2018, 8:10 AM
mhigham-moore
mhigham-moore - avatar
3 odpowiedzi
+ 1
Generally, you should consider var to be a non-factor in terms of performance. I use var when the initialization of the variable clearly tells me what the variable will contain. Var exists to help you generalize something you already know. However, using var makes it hard to know what type the underlying variable actually is. Examples of where I use var are: var age = 17; var customer = new Customer(); etc As you are new to programming you will unlikely notice the difference in using var or stating the actual data type. However, as you progress and write more lines of code, your code might be prone to above mentioned issue. Bottom line: use of var does not affect performance, however use it wisely.
29th Aug 2018, 12:50 PM
Ash Devtest
Ash Devtest - avatar
+ 3
i'd recommend using var when the type of the variable has a really long name to avoid typing a lot because the types are determined during compile-time so it won't hurt to use it. but other than that it's kinda unnecessary as it can somewhat hurt code readability
29th Aug 2018, 9:05 AM
hinanawi
hinanawi - avatar
+ 1
Please don't in my opnion it is bad practice. C# is strongly typed, use that as an advantage. Of course nowadays var is also strongly typed because it type is define on initialisation. If you know something is going to be a string, call it a string. It makes your code more readable, and prevent strange difficult to debug bugs. I only use var if this variable can hold multiple variable types, not so often. https://www.intertech.com/Blog/the-use-and-abuse-of-the-c-var-keyword/
29th Aug 2018, 11:08 AM
sneeze
sneeze - avatar