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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With