Generic type implementers, class and interface versions not compatible


H

HC

I've stripped down my code to barebones to demonstrate (below).

I have interfaces and classes which implement them. I force my generic
collection to accept only the interface type. If I create an instance
of the generic class using the class implemention of the interface I
find it can't be converted to the interface version, and vice versa.
This a pain with my current design.

Can someone please advise on what best practice might be in this
situation. Are there any cardinal rules or similar that I'm violating,
passing an interface to the generic collection instead of an actual
class?

The compiler should know they both support the same interface so why
not compatible?

thanks



interface IMyInterface
{
}

class ImplementsMyInterface : IMyInterface
{
}

class GenericClass<T> where T : IMyInterface
{
}

class TestAbove
{
void MethodWhichTakesClass(GenericClass<ImplementsMyInterface> ts)
{
MethodWhichTakesInterface(ts); // Cannot convert type
'Test.GenericClass<Test.ImplementsMyInterface>' to
'Test.GenericClass<Test.IMyInterface>'
}
void MethodWhichTakesInterface(GenericClass<IMyInterface> ts)
{
MethodWhichTakesClass(ts); // cannot convert from
'Test.GenericClass<Test.IMyInterface>' to
'Test.GenericClass<Test.ImplementsMyInterface>'
}
}
 
Ad

Advertisements

H

HC

I might know what I have to do.

I have child interfaces which inherit a parent interface, and class
implementations. The parent class/interface is what I use as a
parameter to the generic collection, using the interface where I want
it to store all inherited types.

I don't actually inherit from the parent class in my child classes,
only from the child interfaces (which inherit the parent), so I'm
implementing the parent independently in each child.

Maybe I need to inherit child classes from the parent class, and then I
might be able to get away with using the parent class always in my
generic collection.

???
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top