Search code examples
c#staticcall

Can't Set variable value in Static Field


In this simple example Why StrA in Sample() function Can't set with "Hi World" string ?

string StrA { get; set; }

private void button1(object sender, EventArgs e)
{
    StrA = "Hi World";   //=======>   Get StrA value
}


public static string Sample()
{
    MyClass MyClass1 = new MyClass();

    string a = MyClass1.StrA;  //==========> Can't Set StrA value with "Hi World" string ???

    return (MessageBox.Show(a).ToString());
}

Solution

  • make StrA a static field, right now it's just a local property of the instance, so when you create a new instance with MyClass1 = new MyClass();

    the StrA property is empty (null) and even if you set it a value, after you create a new instance that new instance will have SrtA as empty...