Home > OS >  C# variable assignment can not be obtained
C# variable assignment can not be obtained

Time:11-07

public void textServername_TextChanged(object sender, EventArgs e)
{
    _sn = textServername.Text;
}

public static string connectionString =  _sn ;

connectionString Why can't get the assignment of _sn

CodePudding user response:

Although string is a reference type, it acts like a value type. When connnectionString is initialized , it gets the value of _sn at the time of initialization. Updating the value of _sn would not be reflected by conntectionString. If you want value to be reflected, you can use a property instead like below.

public static string ConnectionString
{
    get => _sn;
}

CodePudding user response:

You can use static constructor.A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed only once. It is called automatically before the first instance is created or any static members are referenced.

class SimpleClass
{
    // Static variable that must be initialized at run time.
    static string ConnectionString ;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        ConnectionString = "connection string";
    }
}
  •  Tags:  
  • c#
  • Related