Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global instances of class

Still trying to get to know C# (Mostly worked with C). I have a class "Device" and would like to create an instance of the class, but would also like access to the instances globally because I use them so much in my GUI methods.

 public class Device
    {
        public string Name;
        public List<string> models = new List<string>();
        public List<string> revisions = new List<string>();
        ...
    }

Somehow declare this globally:

 Device Device1 = new Device();
 Device1.Name = "Device1";

Then access it later in a WPF method:

 private void DeviceViewItem_Selected(object sender, RoutedEventArgs e)
    {
       TreeViewItem selected = (TreeViewItem)sender;

        if (selected.Name == Device1.Name)
        {
            Device1.Models.Add("something");
            Device1.Revisions.Add("something");
        }

I've been reading about singleton Pattern, but it looks like you have to create a Singleton Class, but my "Device" Class is used multiple times to create many devices. Maybe I just don't understand the pattern that well.

like image 832
DevynB Avatar asked Jan 12 '23 23:01

DevynB


1 Answers

Create a new instance and assign it to a static property or field:

public class AnyClass
{
    public static readonly Device ThisFieldCanBeReachedFromAnywhere = new Device();
}

Note that the class AnyClass doesn't have to be static (that would however mean that all members must be static).

Also note that the readonly keyword isn't required, it is just good practice for singletons (like Mark suggested in his comment).

like image 111
lightbricko Avatar answered Jan 22 '23 10:01

lightbricko