Friday, 7 July 2017

c# - Inheriting from List




What is the fastest way to implement a new class that inherits from List?



class Animal {}

class Animals : List {} // (1)


One problem I've encountered: By simply doing (1), I've found that I'm not getting the benefit of inheriting any constructors from List.




In the end, I'd like Animals to behave a lot like a List (e.g., can be constructed, compatibility with Linq). But in addition, I'd also like to be able to add my own custom methods.


Answer



If you want to create a publicly exposed animal collection you should not inherit from List and instead inherit from Collection and use the postfix Collection in the class name. Example: AnimalCollection : Collection.



This is supported by the framework design guidelines, more specifically:




DO NOT use ArrayList, List,
Hashtable, or Dictionary in
public APIs. Use Collection,

ReadOnlyCollection,
KeyedCollection, or
CollectionBase subtypes instead. Note
that the generic collections are only
supported in the Framework version 2.0
and above.



No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...