4
votes

The whole Error Message:

The model item passed into the dictionary is of type
'MyClass`2[Implementation1,Implementation2]', 
but this dictionary requires a model item of type 
'MyClass`2[Interface1,Interface2]'.

In my View, I have the model declaration:

@model MyClass<Interface1, Interface2>

Where MyClass is a Class and Interface1 and Interface2 are interfaces

on my Controller Action I am calling:

return View(model);

where: model is of type...

MyClass<Implementation1,Implementation2>

...and Implementation1 implements Interface1 and Implementation2 implements Interface2

Is there any way to avoid this error, without having to declare my model as below?

@model MyClass<Implementation1, Implementation2>
1
Any reason you can't make your model use MyClass<Interface1, Interface2>?DavidG

1 Answers

3
votes

Because MyClass is invariant you can not do this, that means MyClass<Implementation1, Implementation2> is not MyClass<Interface1, Interface2>, hence the error.

As it's not an interface or a delegate, the class cannot to be declared as covariant. Although you can create an interface and make it covariant using out keyword:

public interface IMyClass<out T1, out T2>
{
    ...
}

public class MyClass<T1, T2> : IMyClass<T1, T2>
{
    ...
}

The model declaration in the View:

@model IMyClass<Interface1, Interface2>