var keyword | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

var keyword

What is the output of this code? var n1; n1 = true; Console.WriteLine(n1); the output of this code is ERROR why not TRUE?

19th Nov 2016, 2:11 PM
beth wangari
beth wangari - avatar
4 Answers
+ 7
When you use the keyword 'var' to specify a variable, you have to immediately state what the variable contains. Otherwise the keyword 'var' will not know what to name itself in order to let 'n1' contain the correct items. It is like telling someone to place a empty box into a correct category when you have not even placed any items into it yet. The correct way would be : string n1; n1 = "true"; Console.WriteLine(n1); OR var n1 = "true"; Console.WriteLine(n1);
19th Nov 2016, 2:49 PM
Wen Qin
Wen Qin - avatar
+ 2
when you declared a variable as type var this mean that you are use that variable for save any kind of type example: var n ; n= 1 n=1.3 n=true n= "hi" that variable can accept that a save anything I can save a list or a colection is like if you create a variable type object this mean that this variable could be whatever you want
19th Nov 2016, 6:23 PM
Jorge Sánchez
Jorge Sánchez - avatar
+ 1
Implicitly-typed local variables must be initialized
17th Feb 2017, 8:51 PM
Vira Yanchuk
Vira Yanchuk - avatar
0
Because when you use the 'var' keyword, the variable must be initialized at the same time you declare it. So in that example, you have to write it as: var n1 = true; This is different from if you were to use the data types (int, double, bool...etc), because they allow you to declare a variable and initialize it later. So, if you were to have written: bool n1; n1 = true; This would be ok because you used the data type.
26th Nov 2016, 12:45 PM
Jess
Jess - avatar