I’m trying to understand why the following will not compile. The compiler complains on the line where CreatePresenter tries to set the View property:
Cannot implicitly convert type ‘Sandbox.Program.MyView’ to ‘TView’.
I know the context of the assignment does not make sense, it’s more for illustration. Any help would be great!
interface IView {
}
class Presenter<T> where T : IView {
public T View { get; set; }
}
class MyView : IView {
}
class MyPresenter : Presenter<MyView> {
public MyPresenter() { }
}
class ViewBase<TPresenter, TView>
where TPresenter : Presenter<TView>, new()
where TView : IView {
public TPresenter Presenter { get; private set; }
void CreatePresenter() {
this.Presenter = new TPresenter();
this.Presenter.View = new MyView();
}
}
On the line:
you’re trying to set a
MyViewobject to a property of generic typeTView(implementingIView).This is wrong because
MyViewis different fromTViewso it can’t be assigned.EDIT:
To expand a bit…
You can assign a type to its interface e.g. :
but you can’t assign an interface to one of its implementers e.g.:
Here you’re doing something more convoluted, something like this:
That is clearly wrong.
In fact, even if
TViewandMyViewimplement the same interface, to allow thisTViewshould inherit fromMyViewbut that’s not specified among the generic constraints, and so the compiler can’t do any assumption.Have a look also to davy8’s answer for a clear example 🙂