I have a class with a private static List<String> collection. Now I want to return a readonly list. Would this be the ideal way of doing it? Would you do it another way? Is this the proper way?
namespace Test
{
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 System.Collections.ObjectModel.ReadOnlyCollection<string>getList
{
get
{
return stores.AsReadOnly();
}
}
public static void addString(string add)
{
store.Add(add);
}
}
}
It depends on client expectations. If your clients expect that the contents of the list can change, then that’s (vaguely) okay. If they’re expecting an unchanging collection, then you’ll need to take a copy.
Note that
List<T>isn’t thread-safe to start with, which is a big red warning light when it comes to global mutable state, accessed with no obvious synchronization…(Having global mutable state is an issue to start with, IMO, affecting testability etc. Doing so in an unsafe way just makes it even worse.)