Search code examples
c#ilist

How to implement a fixed-sze generic IList in C#


I'm building a special collection that needs to implement the generic IList<> interface. The thing is, I want the collection to act like a non-generic fixed-size IList. I don't want the user to be able to insert or remove objects into the collection.

The IList interface doesn't implement the IsFixedSize property for some reason. So what's the best way to do this with the generic IList interface? I could just let the Insert, Remove and RemoveAt methods throw NotImplementedException, and I'd be OK with that, but is there a better, more accepted way?

Tony


Solution

  • One typical way would be to explicitly implement the offending members of IList like Add, Insert, and Remove, so that they aren't available to people unless they actually cast your thing to IList. That's how arrays do it.