Generics and base constraint ?

  • Thread starter Thread starter Bernhard Huemer
  • Start date Start date
B

Bernhard Huemer

using System;
using System.Collections.Generic;

public class CovariantList<T> : List<T>
{
// ...

// of course this constraint won't work ..
public CovariantList<U> Convert<U>() where U: base T {
CovariantList<U> list =
new CovariantListList<U>(this.Capacity);

IEnumerator<T> enumerator = this.GetEnumerator();
while(enumerator.MoveNext()) {
list.Add(enumerator.Current);
}

return list;
}

// ...
}


I've been searching for a constraint to ensure following expression:
T t = /* .. */;
U u = t;

got the point ? if not consider following code:

public class CovariantList<T> : List<T>
{
// ...

// it's quiet plain to me that this overload is useless ..
public void Add<U>(U item) where U: T {
// now i'm able to write:
T t = item;

// how to do it the other way round ?
}

// ...
}

thanks
 
Bernhard,

This can't be done. The reason is that there is not an implicit
operation to convert T to U. The reverse is true, because U derives from T,
so you can just cast down to T.

In order to do something like this, you would have to do:

public class CovariantList<T> : List<T>
{
// ...

// of course this constraint won't work ..
public CovariantList<U> Convert<U>() where U : T {
CovariantList<U> list =
new CovariantListList<U>(this.Capacity);

// The converted item.
U convertedItem;

IEnumerator<T> enumerator = this.GetEnumerator();
while(enumerator.MoveNext()) {
// Perform the conversion here.
convertedItem = /* Do something here to convert
enumerator.Current */;
list.Add(convertedItem);
}

return list;
}

// ...
}

Hope this helps.
 
Well, thanks for the quick answer.
This can't be done. The reason is that there is not an
implicit operation to convert T to U. The reverse is true,
because U derives from T, so you can just cast down to T.

... and therefore i was trying to force U on being a super type of T.
Anyway i'm able to constrain U to be a sub type of T, so i thought it
could be possible ..

Seems not to be possible.
 
Back
Top