views:

270

answers:

7
+1  Q: 

if question

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

+7  A: 

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.

Mehrdad Afshari
+10  A: 

Try something like this

{
    string nom;
    string ou = String.Empty;
    nom = "1";
    if (nom == "1")
    {
        nom +=1;
        ou = nom;
    }
    Console.Write(ou);
}
Jedi Master Spooky
+3  A: 

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.

AdamRalph
+3  A: 

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.

Anton Gogolev
To whoever downvoted this: what exactly don't you agree with?
Anton Gogolev
I did not downvote it, but my issue with it is the ="", it should be = String.Empty for readability reasons mostly.
Alex
+5  A: 

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.

Martijn
+5  A: 

Does this even compile?

nom is a string - how can you do nom += 1?

teedyay
The same way string foo = "User id=" + 10; works. The result is "User id=10". Here, nom would be "11". That might not be the expected result, admittedly...
Jon Skeet
1 will be converted to string before concatenation. it's equal to nom += 1.ToString()
abatishchev
Well I never! I'm really surprised the compiler lets you do that...
teedyay
A: 

Another option is to set ou in an else:

if (nom == "1")
{
    nom +=1;
    ou = nom;
} else 
{
    ou = "blank value";
}
GeekyMonkey