Tech
Forums
Jobs
Books
Events
Videos
Conference
Annual Conference
Bcrypt
Ai Conference
Live
More
Interviews
Certification
Training
Career
Members
News
Blogs
Contribute
An Article
A Blog
A Video
An Ebook
An Interview Question
Register
Login
0
Answer
Casting typed collections
Ask a question
Ask a question
Upload Source Code:
Select only zip and rar file.
Robert Robson
18y
1.7k
1
Reply
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!
Post
Reset
Cancel
Answers (
0
)
Next Recommended Forum
Reading/Sorting/Searching XML File
Exception Handling