How to create a flexible extension method for generic lists?

Up vote 0 down vote favorite share g+ share fb share tw.

I have 2 objects Project and License. They both inherit from the object Entity (abstract class). Now I have an extension method "GetNewId" that contains logic to get the next id in a list of entities.

I've defined this method as an extension method, but the problem is that List (which is also a list of entities) and List don't see this method. I guess that this problem will occur with any generic list containing objects that inherit from the same base class. Is there a solution for this problem?

Edit: working in C# c# generics inheritance extension-methods generic-list link|improve this question edited Dec 8 '09 at 12:23 asked Dec 8 '09 at 10:40user299642,05452339 98% accept rate.

– Avi Dec 8 '09 at 11:29 sorry mate. I'm so used to it ... – user29964 Dec 8 '09 at 12:23.

If you make it an extension of IEnumerable - where T is restricted to be derived from your Entity base class - you should be able to use the extension method on any collection like class containing Entity based objects: public static GetNewId(this IEnumerable sequence) where T : Entity { // your implementation of GetNewId here } The Cast method (from System. Linq) is also defined on IEnumerable (but on any type T, no restrictions), hence you can use it on your licenses instance.

This doesn't work, it won't compile, there is an error near the where (it says) – user29964 Dec 9 '09 at 7:21 Your example contained Tedu.LicenseWebsite.Core.Model.Entity. You do know about the using statement and namespaces...? – peSHIr Dec 10 '09 at 13:24.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions