-7

My code is:

        if (textBox1.Text != "")
        {
            StreamReader tx = new StreamReader(textBox1.Text);
        }
        else
        {
            StreamReader tx = new StreamReader("new.txt");
        }

        string line;

        while ((line = tx.ReadLine()) != null)
        {

If i delete "if" and leave it as:

        StreamReader tx = new StreamReader("new.txt");


        string line;

        while ((line = tx.ReadLine()) != null)
        {

Everything works. Why does if mess up my code?

Ham Burg
  • 51
  • 5
  • 1
    A variable declared inside a block `{ ... }` is visible only inside that block. Declaring the StreamReader inside the `if { }` block doesn't allow it to be used outside of it, Declaring it inside the method block allows it to be used everywhere inside that method block. This is basic knowledge required to program in C# (and the concept is useful everywhere). Please read something about [C# Scopes](https://msdn.microsoft.com/en-us/library/aa691132(v=vs.71).aspx) – Steve Feb 27 '16 at 14:49

1 Answers1

0

Change your code to:

   StreamReader tx;
   if (textBox1.Text != "")
   {
      tx = new StreamReader(textBox1.Text);
   }
   else
   {
      tx = new StreamReader("new.txt");
   }

You can learn more here: C# local variable scope

Community
  • 1
  • 1
romanoza
  • 4,775
  • 3
  • 27
  • 44