471,327 Members | 2,678 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,327 software developers and data experts.

Generic type implementers, class and interface versions not compatible

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

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


interface IMyInterface

class ImplementsMyInterface : IMyInterface

class GenericClass<T> where T : IMyInterface

class TestAbove
void MethodWhichTakesClass(GenericClass<ImplementsMyInt erface> ts)
MethodWhichTakesInterface(ts); // Cannot convert type
'Test.GenericClass<Test.ImplementsMyInterface>' to
void MethodWhichTakesInterface(GenericClass<IMyInterfac e> ts)
MethodWhichTakesClass(ts); // cannot convert from
'Test.GenericClass<Test.IMyInterface>' to

Feb 14 '06 #1
1 1499
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.


Feb 14 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

49 posts views Thread by Steven Bethard | last post: by
4 posts views Thread by Jethro Guo | last post: by
3 posts views Thread by BombDrop | last post: by
13 posts views Thread by rkausch | last post: by
10 posts views Thread by phancey | last post: by
4 posts views Thread by tadmill | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.