I've got a static class, called Test, and a private List collection. Now I want to implement a getter to return my List to the main class. Is this the correct way?
Secondly is it okay to implement a static constructor? If not, how do I properly declare my List Collection?
static class Storage
{
private static List<string> store;
static Storage()
{
store = new List<string>();
}
//Is it okay to have a getter in my static class to return my List Collection
public static List<string> getList
{
get
{
return store;
}
}
public static void addString(string add)
{
store.Add(add);
}
public static void removeString(string remove)
{
store.Remove(remove);
}
If you return a reference to the list in the getter then any caller can add or remove items from the list without going through the add/remove methods on the static class. If you want to prevent anyone from modifying the list I would return a read only collection from the getter:
public static IEnumerable<string> getList
{
get
{
return store.AsReadonly();
}
}
Edit
As Marc pointed out you will need to watch out for multi threading issues. Imagine one thread enumerates the collection obtained via the getter while another thread modifies it by add or removing an item -> you will get an exception saying that you can't modify a collection while enumerating it. The only solution for that is to lock all access to the private collection and return a copy in the getter.
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