If you need a collection that you can edit but not delete from, here's something I've used in the past:
- using System;
-
using System.Collections.Generic;
-
using System.Collections;
-
using System.Linq;
-
-
namespace Example
-
{
-
class Program
-
{
-
static void Main()
-
{
-
ReadOnlyList<string> list = new ReadOnlyList<string>();
-
list.Add("something");
-
list.Add("else");
-
list.Add("test");
-
foreach (string s in list)
-
Console.WriteLine(s);
-
var sub = list.Where(x => x.Contains("t"));
-
foreach (string s in sub)
-
Console.WriteLine(s);
-
Console.ReadKey();
-
}
-
}
-
-
public class ReadOnlyList<T> : IEnumerable<T>
-
{
-
private List<T> list;
-
-
public ReadOnlyList()
-
{
-
list = new List<T>();
-
}
-
-
public ReadOnlyList(IEnumerable<T> collection)
-
{
-
list = new List<T>(collection);
-
}
-
-
public void Add(T item)
-
{
-
list.Add(item);
-
}
-
-
public void AddRange(IEnumerable<T> collection)
-
{
-
list.AddRange(collection);
-
}
-
-
public void Insert(int index, T item)
-
{
-
list.Insert(index, item);
-
}
-
-
public void InsertRange(int index, IEnumerable<T> collection)
-
{
-
list.InsertRange(index, collection);
-
}
-
-
public T this[int i]
-
{
-
get { return list[i]; }
-
set { list[i] = value; }
-
}
-
-
public int Count { get { return list.Count; } }
-
-
#region IEnumerable Members
-
public IEnumerator GetEnumerator()
-
{
-
return list.GetEnumerator();
-
}
-
#endregion
-
-
#region IEnumerable<T> Members
-
IEnumerator<T> IEnumerable<T>.GetEnumerator()
-
{
-
return list.GetEnumerator();
-
}
-
#endregion
-
}
-
-
public static class ExtensionMethods
-
{
-
public static ReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> collection)
-
{
-
return new ReadOnlyList<T>(collection);
-
}
-
}
-
}
The basic idea is to implement IEnumerable<T>. That way, you get all the LINQ extension methods, and you can easily do foreach loops. Also, I've added an indexer, so you can treat it like an array if you want.
You can add/remove methods as needed, but you can see the pattern here.
It's a little different than inheriting from List, because with list, you still have the methods the base class has. Then, you'd have to throw exceptions or (worse) do nothing when those undesirable methods are called. In this way, you can just treat it like any other IEnumerable. System.Linq even includes a ToList extension method.
If you just wanted to be able to add, but not insert, or whatever, you could remove those methods. But if the AsReadOnly method works for you, that's a great solution too.
Also tacked on an extension method to turn other IEnumerables into a ReadOnlyList.