- Home /
Checking null variable error
bool empty;
if (empty == null){
//do something
}
Use of unassigned local variable. This doesn't make any sense. How do I fix this?
Answer by tanoshimi · Sep 19, 2014 at 01:25 PM
What doesn't make any sense? empty
is unassigned, as the error message states. You fix it by assigning a value to the variable, which can either be on the same line as the declaration, or any time before it is used.
Since bool is not a nullable type, you must either assign it the value true or false:
bool empty = false;
if (empty == false){
//do something
}
Or, if you're using a nullable type such as a string, you could assign a null value as follows:
string empty = null;
if (empty == null){
//do something
}
But a bool can never be null, so the if statement will never be true...
Ok, Avash. As Tanoshimi says, you can use nullable types. In your case it will be like this:
bool? empty = null;
if (empty == null){
// do something
// and for example:
empty = true;
}
Answer by Lex_87 · Sep 19, 2014 at 01:36 PM
Boolean is value type in .NET FCL type library. Value types hasn't null state. In C# idiomas you have to initialize local variables, then use them in the same context. Except that cases where you guaranteed take a value through ref keyword. In this case local variable initialization will be redundant. As Tanoshimi says you can initialize first and use them safe below.
Your answer
Follow this Question
Related Questions
simple animation 1 Answer
Semicolons are seen as an unexpected symbol 1 Answer
Convert type `float' to `bool', Load 1 Answer
Delay between animations 1 Answer
Error Java script 1 Answer