Problem with variable

Hi there ... i can't understand why compiler can't find varible if i have declared it...
please look at this code:

private void button1_Click(object sender, EventArgs e)

{

bool found;

string[] array1 = { "Mikus", "Anda", "Juris" };

for (int i = 0; i < array1.Length; i++)

{

if (array1Idea == textBox1.Text)

{

found = true;

MessageBox.Show("Atradu mekl to v rt bu. " + array1Idea + " ir mas va " + i + ". elements");

}

}

if (found != true)

MessageBox.Show("Nor d t v rda sarakst nav");

I get following error:

Error 1 Use of unassigned local variable 'found'





Answer this question

Problem with variable

  • bt8114

    You're just declaring the variable "found", but it's not set to anything. Set it to false to fix this:

    bool found = false;



  • TheSteve


     bool found;
     for (int i=0; i < 5; i++)
     {
      found = true;
     }
     Console.WriteLine(found.ToString());

     
    The compiler knows that all logic paths lead to an assignment to found before the WriteLine call is made.  Whereas something like this is not guarenteed to assign/initialize found before WriteLine is called:


    bool found;
    switch(someValue)
    {
    case 0:
     found = true;
    case 1:
     found = false;
    }
     Console.WriteLine(found.ToString());

     

    If someValue does not equal 0 or 1, then found does not get initialized and the compiler will give you a warning.

  • Mediocretes

    Hello Mix,
       That is not the error that you are receiving.  The error is that found is not always assigned a value before you use it.  You can either and an else statement to assign found = false, or you can assign found = false when you delclare it.

    bool found = false;

  • steveQ56

    Assign initial value to your variable:

    bool found = false;

    This is becouse C# does basic checks for definite assigment of variables. In case if it see for loop - it assume that this possible that it will be never executed. As well - your conditional if   make it possible that value will be never assigned.


  • Joachim Juell

    Hi,

    Guys, in reality this also confuses me. Some statements work even if you don't initialize your vars and some doesn't.

    eg

       bool found;
       for (int i=0; i < 5; i++) {
        found = true;
       }
    //   found = true;
       Console.WriteLine(found.ToString());

    this generates an error. As you notice, the code actually would pass in the loop and thus set it to true (so why doesn't the compiler allow this ). But if I remove the quote on the found = true this wouldn't generate any error...

     

    cheers,

    Paul June A. Domag



  • Problem with variable