c# - About Generics and Inheritance (forgive my bad title) -



c# - About Generics and Inheritance (forgive my bad title) -

as don't know how problem called, cannot guarantee, nobody has asked same question or @ all.

i did notice, there quite few threads similar title, don't seem relevant problem.

i have custom list class, implements generics.

class mylist<t> { public void add(t item) // adds item list { /* code */ } public void add(mylist<t> list) // attaches existing list end of current 1 { /* code */ } }

i have classes:

class apple : fruit

and

class banana : fruit

now, comes relevant code:

mylist<fruit> fruitlist = new mylist<fruit>(); // fill fruitlist fruitlist.add(new apple()); // works, of course of study fruitlist.add(new banana()); // works well, of course of study mylist<apple> applelist = new mylist<apple>(); // fill applelist fruitlist.add(applelist); // doesn't work. why?

even though applelist mylist(of apple) , apple fruit, visualstudio doesn't take mylist(of apple) argument, when mylist(of fruit) asked.

however, if declare list this:

mylist<object> fruitlist = new mylist<object>();

then works again. did wrong?

an reply much appreciated, , give thanks taking time read, without answering.

you're trying utilize covariance. .net supports generic variance on interfaces, won't work.

in addition, covariance makes sense on immutable types. had been possible convert mylist<apple> mylist<fruit>, able add together orange list, violating type safety.

instead, can create method generic:

public void add<u>(ilist<u> list) u : t

c# generics covariance

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -