Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Class and Getter

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);
   }
like image 815
Sylvia Rosemond Avatar asked Feb 20 '23 07:02

Sylvia Rosemond


1 Answers

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.

like image 176
ChrisWue Avatar answered Feb 27 '23 09:02

ChrisWue