Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcards in C# generic constraints

I'm aware that C# doesn't have generic wildcards, and that a similar effect can be achieved by generic methods, but I need to use a wildcard in a field and can't work out if there is any way to encode it.

List<State<Thing>> list;

void AddToList<T>() where T : Thing {
    list.Add(new State<T>());
}

Of course, this doesn't work because the object being added isn't of type State<Thing>, it's of type State<T> where T : Thing. Is it possible to adjust the most internal type of the list to be the Java equivalent of ? extends Thing rather than just Thing?

like image 751
zmthy Avatar asked Dec 08 '11 07:12

zmthy


1 Answers

Note that C# 4 does have additional variance support, but it does not apply in the List<T> case, for various reasons (has both "in" and "out" methods, and is a class).

I think, however, the way to address this is with something like:

interface IState { // non-generic
    object Value { get; } // or whatever `State<Thing>` needs
}
class State<T> : IState {
    public T Value { get { ...} } // or whatever
    object IState.Value { get { return Value; } }
}

and

List<IState> list; ...

which will then allow you to add any State<T>. It doesn't really use much of the T, and a cast would be needed to get from the object to T, but .... it will at least work.

like image 123
Marc Gravell Avatar answered Oct 21 '22 11:10

Marc Gravell