TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Robert Robson
NA
1
0
Casting typed collections
Jun 14 2006 11:06 AM
Hello everybody! I have come upon a problem when using typed lists in .Net 2.0: it is impossible to cast a list of an implementing type to a list typed to the implemented interface.
e.g.:
class
Program
{
static
void
Main(
string
[] args)
{
List
<
Banana
> bananas =
new
List
<
Banana
>();
List
<
IFruit
> fruitsFail = bananas;
//Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<CastExample.Banana>' to 'System.Collections.Generic.List<CastExample.IFruit>'
List
<
IFruit
> fruitsWork =
new
List
<
IFruit
>();
foreach
(
Banana
b
in
bananas)
fruitsWork.Add(b);
}
}
interface
IFruit
{ }
class
Apple
:
IFruit
{ }
class
Banana
:
IFruit
{ }
As you see i am able to iterate through the collection and cast every element to build a new list. Can somebody tell a more elegant way to get a list typed to the interface or point to my error in reasoning? Thanks a lot!
Reply
Answers (
0
)
Reading/Sorting/Searching XML File
Exception Handling