matt
matt

Reputation: 4244

C# polymorphism in Generic types

class Base
{}

class Sub : Base
{}


void AddNewBase(Base t, LinkedList<Base> list){ ... }
...
{

    Sub asub = new Sub();

    LinkedList<Sub> asubList = new LinkedList<Sub>();
    AddNewBase(asub,asubList) // doesn't work
}

basically, I have a custom insert function that takes a new item and a list to put it in, and it does some 'sorting' stuff to find a good place to put it in the list.

problem is, I want to do this based on properties in 'Base' so it would be good to have just one function that could do this for all lists of sub types.

I think what I kind of want is:

static void AddNewBase<T>(T t, LinkedList<T> list){ ... }

but with some way of clarifying T like: 'where T is a sub class of Base'

Upvotes: 5

Views: 1629

Answers (3)

Bradley Smith
Bradley Smith

Reputation: 13601

In C# 4, you can use covariance to make this work. You have to select from one of the covariant generic collection interfaces though. For example, redeclaring your method as:

static void AddNewBase(Base t, IEnumerable<Base> list) { //... }

Would allow you to call AddNewBase with a LinkedList<Sub>.

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

You can use where keyword in the same way and you do not need a generic type.

Here is the IComparable implementation which probably is what you could be looking for in a classic sorting problem:

    static void AddNewBase<T>(T t, LinkedList<T> list) where T : IComparable
    {
        //
    }

Upvotes: 0

dtb
dtb

Reputation: 217293

You can declare Constraints on Type Parameters:

static void AddNewBase<T>(T t, LinkedList<T> list) where T : Base { ... }

Upvotes: 9

Related Questions