Properly exposing a List<T>?
.net, c#
Solution
Use AsReadOnly() - see MSDN for details
Problem
I know I shouldn't be exposing a `List<T>` in a property, but I wonder what the proper way to do it is? For example, doing this: ``` public static class Class1 { private readonly static List<string> _list; public static IEnumerable<string> List { get { return _list; //return _list.AsEnumerable<string>(); behaves the same } } static Class1() { _list = new List<string>(); _list.Add("One"); _list.Add("Two"); _list.Add("Three"); } } ``` would allow my caller to simply cast back to `List<T>`: ``` private void button1_Click(object sender, EventArgs e) { var test = Class1.List as List<string>; test.Add("Four"); // This really modifies Class1._list, which is bad™ } ``` So if I want a really immutable `List<T>` would I always have to create a new list? For example, this seems to work (test is null after the cast): ``` public static IEnumerable<string> List { get { return new ReadOnlyCollection<string>(_list); } } ``` But I'm worried if there is a performance overhead as my list is cloned every time someone tries to access it?