0

I am trying to monitor the connection status via Status which automatically change the label's text on my form.

This is in my main class

private int _status;
public int Status
{
    get { return _status; }

    set
    {
        _status = value;
        if (_status == (int)ServerStatus.Disconnected)
        {
            statusLabel.Text = "Disconnected";
            statusLabel.ForeColor = Color.Red;
        }
        else
        {
            statusLabel.Text = "Connected";
            statusLabel.ForeColor = Color.Green;
        }
    }
}

My problem now is how can I change the Status from another class without instantiating the main class. Or is there a better approach to what I am doing?

marneee
  • 25
  • 1
  • 3

1 Answers1

0

You can't access an instance property without a reference to this instance.

To be able to modify a property of an object of type of a class, you need to access this living object by reference to its instance.

Unless this property is static or the class is implemented as a singleton.

Static property

public class MyClass
{
  static private int _status;
  static public int Status
  {
  }
}

MyClass.Status = 1;

In this case, all instances of MyClass share the same _status value that is common for all so there is only one _status in the whole app.

MyClass may be static or not depending of your design.

Singleton

public class MySingleton
{
  public readonly MySingleton = new MySingleton();

  private MySingleton()
  {
  }

  private int _status;
  public int Status
  {
  }
}

MySingleton.Instance.Status = 1;

In this case, only one instance of the class is allowed so there is only one _status in the whole app.

Difference between static class and singleton pattern?