+ 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...
7 Answers
+ 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!
+ 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.
+ 4
Basically that is what I meant, AbdĂŒlcelil. In addition, the compiler might decide something contrary to your intended variable type.
+ 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.
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
0
It allows implicit typing of variables allowing the compiler to determine the intended type instead of explicitly declaring that variables type.
0
@ChaoticDawg i am asking why do we need bool, double, string.. if we have "var"