+ 1

What is the purpose of "var" in c#?

If usage of "var" understand automaticaly what is the type of it (int, bool, double...) why do we use these types? Writing directly "var" will be easier. Why we made it hard from the beginning? var a = true; Console.WriteLine(a); bool a = true; Console.WriteLine(a); same output...

18th Feb 2017, 9:17 PM
Abdülcelil Arslan
Abdülcelil Arslan - avatar
7 odpowiedzi
+ 5
var creates a variable whose type depends on the value you initialize it with. Ex: var num = -5 makes it an int, var flag = false makes it a bool, etc. It should *not* be depended on for an exact result! What you get may not be what you expect. What it's best used for is objects and working with Windows forms, where the type is already written there. Ex: var User = new Customer(); //It will *always* be a Customer object!
19th Feb 2017, 12:29 AM
Tamra
Tamra - avatar
+ 4
var makes for confusing and difficult code. Strongly typed languages are the best in this sense - you can easily understand what the code is doing.
18th Feb 2017, 9:41 PM
Varun Ramani
Varun Ramani - avatar
+ 4
Basically that is what I meant, Abdülcelil. In addition, the compiler might decide something contrary to your intended variable type.
18th Feb 2017, 10:40 PM
Varun Ramani
Varun Ramani - avatar
+ 2
Ah, sorry misread that. It's usually best to be explicit in your code whenever possible. This allows for easier code readability and stronger type checking and less errors in the long run. This however, doesn't mean that the use of var doesn't ensure type checking as it most certainly does.
18th Feb 2017, 10:22 PM
ChaoticDawg
ChaoticDawg - avatar
0
@Varun Ramani so you mean you can use it but it will be hard to understand for another person or you in the future :D
18th Feb 2017, 10:00 PM
Abdülcelil Arslan
Abdülcelil Arslan - avatar
0
It allows implicit typing of variables allowing the compiler to determine the intended type instead of explicitly declaring that variables type.
18th Feb 2017, 10:09 PM
ChaoticDawg
ChaoticDawg - avatar
0
@ChaoticDawg i am asking why do we need bool, double, string.. if we have "var"
18th Feb 2017, 10:12 PM
Abdülcelil Arslan
Abdülcelil Arslan - avatar