Static Class and Getter

11,981

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.

Share:
11,981
Sylvia Rosemond
Author by

Sylvia Rosemond

Updated on June 04, 2022

Comments

  • Sylvia Rosemond
    Sylvia Rosemond about 2 years

    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);
       }
    
  • Sylvia Rosemond
    Sylvia Rosemond almost 12 years
    Thanks Daniel. Your correct about my method names. I was just playing around with C#. So, the way I have my getter implemented to return my List collection is the correct way?
  • Daniel Mann
    Daniel Mann almost 12 years
    Yes, that's fine. Although the add and remove methods you have are redundant.
  • Sylvia Rosemond
    Sylvia Rosemond almost 12 years
    Thanks Chris. Instead of IEnumerable, can I say ICollection?
  • ChrisWue
    ChrisWue almost 12 years
    Yes, you could return ICollection instead
  • Sylvia Rosemond
    Sylvia Rosemond almost 12 years
    Lets say I use ICollection, and call it from my main program, how would I loop though it to see the string values?
  • ChrisWue
    ChrisWue almost 12 years
    foreach (string value in Storage.getList) { ... }