0

What's a 'var' datatype?

I want to know what is a 'var' datatype? I always saw it written into the codes but never learn what it is and when to use it.

15th Oct 2016, 1:33 PM
Geisson Lucas S. de Oliveira
Geisson Lucas S. de Oliveira - avatar
6 Respostas
+ 8
var is a special data type that automatically converts the variable to a different data type, depending on what it's assigned. Because of this, it has to be assigned a value immediately. Ex: "var price = 5.50;" will make price a double. It's not a good idea to rely on this conversion, so it's usually used in situations where the data type is already written there. Ex: "var Names = new List<string>();" will always be a List of strings, it's better than writing the long type name twice.
15th Oct 2016, 9:27 PM
Tamra
Tamra - avatar
+ 6
Oh yeah, that was probably not a good choice for an example...this app doesn't cover it, I don't think. Lists are a bit like arrays, but you don't have to specify how many slots of data you want. You can just add or remove them as needed. You must put a data type in the angle brackets <>. To use List<>, you need to add the line "using System.Collections.Generic;" to the top of the file. Making a List<> is like making an object or array. For why I used it as an example with using var, ordinarily the line to make one would be written: List<string> names = new List<string()>; It's just a bit shorter to use var!
17th Oct 2016, 4:49 AM
Tamra
Tamra - avatar
+ 3
Var is not a datatype. It's a keyword.
17th Oct 2016, 8:36 PM
Ivan G
Ivan G - avatar
+ 1
thakns tamara. now its clear to me. actually i didnt saw any code like your example . thats why i was confused.
17th Oct 2016, 4:55 AM
TalHa
TalHa - avatar
0
can anyone explain this code. plllzzz Ex: "var Names = new List<string>;" will always be a List of strings, it's better than writing the long type name twice
17th Oct 2016, 4:34 AM
TalHa
TalHa - avatar
0
Thanks everyone how help to solve my doubt. Now I know when to use var datatype.
17th Oct 2016, 5:29 PM
Geisson Lucas S. de Oliveira
Geisson Lucas S. de Oliveira - avatar