user1819301
user1819301

Reputation: 111

Static Variable Call from different classes

So Class 1 is called before Class2. Sfile in class 1 contains text and I verified that. While using it in class2 it is null. I know I'm missing something, just can't remember what. Thanks!

public static Class1{
     public static StreamWriter Sfile;

internal static void Function1(){
      StreamWriter Sfile = new StreamWriter(str1, true);
      Sfile.Write(Text)
      }
    }

public partial class Class2{

private void Function2(){
      StreamWriter PrintField=Class1.Sfile;
      //Sfile is null;         
       }
    }

Upvotes: 0

Views: 81

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500675

The problem is that Function1 declares a local variable called Sfile, which hides the static field. So you've given the local variable a non-null value, but not the static field.

Change Function1 like this:

internal static void Function1()
{
    Sfile = new StreamWriter(str1, true);
    Sfile.Write(Text);
}

... and now you won't get the same problem. It's still horrible code for other reasons, but at least Sfile won't be null.

Upvotes: 2

Related Questions