we’ve reached a point where we have no clue how to continue:
SHORT:
We have a generic interface and a collection of the generic interface. Trying to add an implementation of the generic interface to the collection fails. What happens is that I get a compile time exception saying:
cannot convert from TestApp.IState<T>’ to TestApp.IState<TestApp.IView>’
LONG [Code example]:
class Program
{
static void Main(string[] args)
{
var coll = new StateCollection();
var state = new SomeState();
coll.AddState(state);
}
}
public class StateCollection
{
private List<StateBase<IView>> _states = new List<StateBase<IView>>();
public void AddState<T>(StateBase<T> state) where T: IView
{
_states.Add(state);
}
}
public class SomeState : StateBase<SomeView>
{
public IView View
{
get;
}
}
public class SomeView : IView
{
}
public abstract class StateBase<T> where T : IView
{
private SomeView _view;
public SomeView View
{
get { return _view; }
}
}
public interface IView
{
}
Why does this happen? In the AddState we mention that T has to be an instance of IState. Could someone help us out with why this happens and how to do what we want to do?
EDIT1:
We also tried:
public void AddState(IState<IView> state)
{
_states.Add(state);
}
But that just moves the compile time error to ‘coll.AddState(state)’
So the same thing happens in another place.
EDIT2:
PROBLEM! I didn’t give the right example. Out IState is not an interface but an abstract class. Very sorry for that! Changed code to use abstract class
this looks more like a parameter error for the Add function. Have you tried declaring the add function without using the generics? The inheritance itself should allow it. Make the AddState function look like like so:
Edit (as per Edit2):
As mentioned, the inheritance itself should take care of the generics. As long as whatever class you declared properly implements
IView, orIState<IView>, then there shouldn’t be any issues…etc etc and so on, as often as needed
In this case, SomeState is still an IState object, and all IState objects implement IView, and SomeView is an IView object. SomeState implements SomeView internally. Looks the same to me, but I dont know how well the adaption would work with your real code.
Any other classes would follow the same model. The State will implement StateBase, and internally declare a custom View, which itself needs to extend IView. That way the IView cast on the custom view will work.
From comment: