user3634622
user3634622

Reputation: 11

Inheritance (Work with Collection.Generic)

I have:

class A : IHelp

class B : IHelp

Then I want to do such thing like:

List<A> alist = new List<A>();

List<IHelp> hList = (List<IHelp>) alist; // Error!!!

I am a beginner programmer. I will be very grateful to you for detailed answer. Thanks for help!

Upvotes: 1

Views: 51

Answers (2)

SylafrsOne
SylafrsOne

Reputation: 59

Those two classes shares some properties (ex: ToString()) The list could use those properties only

we can do :

List<object> list = new List<object>();
list.Add("foo");
list.Add(5);

foreach(object o in list) 
{
    Console.WriteLine(o.ToString());
}

I've got the same issue.

Will read : http://msdn.microsoft.com/en-gb/library/ee207183.aspx

Here's something weirder :

object[] array = new string[10];        // Possible   <-- /!\ not secured.
List<object> list = new List<string>(); // Impossible

Edit: Yup, I didn't understand your example, meta ^^'

But, we could not want to Add something, just read.

ReadOnlyCollections are not contravariant too :/

Edit 2 : Damn. I've just understood the issue. (the 'out' keyword)

I don't have .NET 4.0 :'( I will use Arrays ^^

(With 4.0 -> IEnumerable makes it possible)

(Using Unity3D)

Upvotes: 0

metacubed
metacubed

Reputation: 7271

You cannot do a cast like this, because it will violate the constraints of the original list. Suppose this works like you said (it actually gives an error, but assume it works):

List<A> aList = new List<A>();
List<IHelp> hList = aList; // Compile error, but say it would have worked..

then, you could have done:

hList.add(new B()); // WHAT??

This does not make sense, because you can never add an element of type B to the original list of type A. This is why C# prevents you from making the assignment you want.

Upvotes: 3

Related Questions