0

Please explain reason for error while using below code

var n1; n1 = "true"; Console.Writeline(n1);

8th Nov 2016, 7:49 AM
Syed Adnan Farogh
Syed Adnan Farogh - avatar
6 Antworten
+ 8
the keyword var is an excellent tool to declare variables since it automatically helps you to search suitable keywords but however, you need to initalize the variable value in order for the keyword var to work. Its like telling someone "Help me to place this box into the correct pile of boxes, I will add in something later. " No, if there is nothing inside that box and you are going to put something in later, how does the person know where to put the box? What if he placed it together with a box of apples and you added orange to it? Its like that logic there, what if the var declared n1 as int and you placed a string there? Hence you need to declare what the variable (n1) contains first.
9th Nov 2016, 3:09 AM
Wen Qin
Wen Qin - avatar
+ 3
could be you did not use capital L on the WriteLine command?
8th Nov 2016, 8:11 AM
Burey
Burey - avatar
+ 3
yup, also should initialize it first
8th Nov 2016, 8:13 AM
Burey
Burey - avatar
+ 3
Variables declared using the var keyword are called implicitly typed variables and must be initialized with a value when you introduce them. Otherwise it will cause an error.
8th Nov 2016, 8:26 AM
Emad Tahmoures
Emad Tahmoures - avatar
+ 1
I used capital L @ Emad: It worked but why do I need to initialize in the line I introduce?
8th Nov 2016, 8:15 AM
Syed Adnan Farogh
Syed Adnan Farogh - avatar
0
I think you should initialize n1 in the line you introduce it by var. Change the first line by: var n1="true"; it will work.
8th Nov 2016, 8:12 AM
Emad Tahmoures
Emad Tahmoures - avatar