var keyword | Sololearn: Learn to code for FREE!


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?

11/19/2016 2:11:24 PM

beth wangari

4 Answers

New Answer


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);


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


Implicitly-typed local variables must be initialized


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.