views:

40

answers:

2

Hello,

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#

A: 

I've found this solution:

licenses.Cast<Tedu.LicenseWebsite.Core.Model.Entity>().ToList().GetNewId();

But now I wonder how slow this is.

Sem Dendoncker
It creates a new `List<Entity>` instance containing the items that are in `licences`, just to be able to call your `GetNewId()` method on that resulting List, that you do nothing else with. I wouldn't do that.
peSHIr
+2  A: 

What class/interface is your GetNewId() method an extension of?

If you make it an extension of IEnumerable<T> - 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<T>(this IEnumerable<T> sequence) where T : Entity {
    // your implementation of GetNewId here
}

The Cast method (from System.Linq) is also defined on IEnumerable<T> (but on any type T, no restrictions), hence you can use it on your licenses instance.

peSHIr
this doesn't work, it won't compile, there is an error near the where (it says)
Sem Dendoncker
Your example contained `Tedu.LicenseWebsite.Core.Model.Entity`. You do know about the `using` statement and namespaces...?
peSHIr