Trauer
Trauer

Reputation: 2091

Inheriting from List<myType> or Extending List<myType>

If I'm creating a class, MyWrapper, to wrap a List of objects from myClass, should MyWrapper inherit from List<T>? Or List<myClass>?

Or should I just create some extension methods for List<myClass>? I know it's against the guideliness to inherit from List<T>, but why?

Is there any drawback for inheriting from List<Point> or List<T>?

Is there any drawback for creating extension methods for List<T>? And what about creating extension methods for List<myType>?

And a example for a extension method valid for List would be

public static void Swap<T>(this List<T> list, int firstIndex, int secondIndex)
{...}

Upvotes: 1

Views: 75

Answers (2)

AFract
AFract

Reputation: 9723

If you choose to derive List<>, the most evident drawback is that your user can't "guess" which method is overriden, and which ones is provided "as is". List is very rich class, especially when extended with LINQ, and a custom overriding of it can quickly be misleading and bug prone.

If you would like to provide List "as is", with a few custom methods, Extension Methods for List (where you target your specific kind of "T" !) could be really helpful and allow to preserve the original behavior of List.

Users will enable and use your Extension Methods only if they need them. The drawbacks are the evident ones of Extension Methods : you can't do everything you want in them. There are plenty informations on web on Extension Methods.

IHMO the best thing to do is to encapsulate the List (or other enumerable) in your own class. Of course, T is specific to your own case. The drawback is the need to redefine all relevant methods. Of course you can also expose the inner list (or, better, a Read only copy of it) with a specific property to allow user to directly use it. Your class can also implement IEnumerable.

Please also note that there are already tons of useful rewriting and extending methods and full custom collection implementation to improve List and other collections types on the web, and in Framework itself (most of collection types are misused, and LINQ adds a lot of good things). Take care to not reinvent the wheel.

Upvotes: 0

Bill Gregg
Bill Gregg

Reputation: 7147

You can't just add extension methods to List, because you won't be able to code to the shape of all types of T. What if it's a List<People>? What would "MoveTo" or "GetCenter" do in that case?

Yes, you should make a new class that inherits from List, or better yet, IList.

Or you could just model your "Point" class, then have a List<Point>, and if you wanted to add extension methods to List<Point> you could do that.

Upvotes: 2

Related Questions