I know I shouldn\'t be exposing a List
in a property, but I wonder what the proper way to do it is? For example, doing this:
public static
Exposing a List
as a property isn't actually the root of all evil; especially if it allows expected usage such as foo.Items.Add(...)
.
You could write a cast-safe alternative to AsEnumerable()
:
public static IEnumerable AsSafeEnumerable(this IEnumerable data) {
foreach(T item in data) yield return item;
}
But your biggest problem at the moment is thread safety. As a static member, you might have big problems here, especially if it is in something like ASP.NET. Even ReadOnlyCollection
over an existing list would suffer from this:
List ints = new List { 1, 2, 3 };
var ro = ints.AsReadOnly();
Console.WriteLine(ro.Count); // 3
ints.Add(4);
Console.WriteLine(ro.Count); // 4
So simply wrapping with AsReadOnly
is not enough to make your object thread-safe; it merely protects against the consumer adding data (but they could still be enumerating it while your other thread adds data, unless you synchronize or make copies).