hi , i have little problem with if
{
string nom;
string ou;
nom = "1";
if (nom == "1")
{
nom +=1;
ou = nom;
}
Console.Write(ou);
}
but i cant print ou value i dont know why
hi , i have little problem with if
{
string nom;
string ou;
nom = "1";
if (nom == "1")
{
nom +=1;
ou = nom;
}
Console.Write(ou);
}
but i cant print ou value i dont know why
C# compiler requires the variables to be definitely initialized before use.
Definite initialization is a compile-time thing, it doesn't consider runtime values of variables.
However, if the variable nom
was explicitly definied as const
, the compiler would be sure that it would not change at runtime and the if
statement block would run and the variable ou
would be definitely assigned to.
Try something like this
{
string nom;
string ou = String.Empty;
nom = "1";
if (nom == "1")
{
nom +=1;
ou = nom;
}
Console.Write(ou);
}
This is because ou is unassigned outside the scope of the if block. Change the declaration line to string ou = string.Empty;
and it shoudl work.
This snippet won't even compile, let alone printing ou
. C# enforces all variables to be initialized before accessing, which is not always true in your case. Thus changing
string ou;
to, say:
string ou = "";
will do just fine.
Try replacing the second line with
string ou = null;
The problem is that if nom turns out not to equal "1", the variable ou won't have been initialized. The compiler here wants to guarantee that ou has been assigned a value.
Does this even compile?
nom
is a string
- how can you do nom += 1
?
Another option is to set ou in an else:
if (nom == "1")
{
nom +=1;
ou = nom;
} else
{
ou = "blank value";
}