Global instances of class

10,469

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).

Share:
10,469

Related videos on Youtube

DevynB
Author by

DevynB

Updated on June 04, 2022

Comments

  • DevynB
    DevynB about 2 years

    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.

    • SLaks
      SLaks almost 11 years
      You're looking for static.
    • Curtis Rutland
      Curtis Rutland almost 11 years
      If you need multiple Singletons, you could look into the Multiton pattern.
  • MJM
    MJM almost 11 years
    possibly making it readonly as well. This is common for the singleton.
  • DevynB
    DevynB almost 11 years
    LightBricko, exactly what I needed. I was looking everywhere and came across Static members, but didn't think of creating a New Instance Statically. Thanks!
  • DevynB
    DevynB almost 11 years
    @Mark Thanks for mentioning readonly. Definitely want to stick with good practices;)