Sylvia Rosemond
Sylvia Rosemond

Reputation: 307

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);
   }

Upvotes: 5

Views: 16748

Answers (2)

ChrisWue
ChrisWue

Reputation: 19030

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.

Upvotes: 9

Daniel Mann
Daniel Mann

Reputation: 59037

You could do private static readonly List<string> store = new List<string>() instead.

Having a property to return your field is the correct way to approach it. You should never have public fields.

Also, while we're on the subject of style: Method and property names should start with capital letters per Microsoft's published naming conventions.

Upvotes: 0

Related Questions