Polymorphic substitutability not supported it seems?

G

Guest

Hi,
When I try to compile this class, I get two compilation errors:

Error 1 The best overloaded method match for
'PolymorphismTest.PolymorphismTest.DoSomethingElse(System.Collections.Generic.IList<object>)'
has some invalid arguments C:\Documents and Settings\aw\My Documents\Visual
Studio 2005\Projects\Reporting\PolymorphismTest.cs 16 13 ReportsGenerator
Error 2 Argument '1': cannot convert from
'System.Collections.Generic.IList<PolymorphismTest.Special>' to
'System.Collections.Generic.IList<object>' C:\Documents and Settings\aw\My
Documents\Visual Studio
2005\Projects\Reporting\PolymorphismTest.cs 16 29 ReportsGenerator


using System;
using System.Collections.Generic;

namespace PolymorphismTest
{
public class PolymorphismTest
{
public void DoSomethingElse(IList<Object> objects)
{

}

public void DoSomething()
{
IList<Special> specialObjects = new List<Special>();
DoSomethingElse(specialObjects);
}
}

public class Special : Object
{

}
}

As far as I can see this should work - I must be missing something?

can anyone help?

Thanks in advance :)
 
J

Jon Skeet [C# MVP]

As far as I can see this should work - I must be missing something?

Yes. IList<SomeType> isn't convertible to IList<Object>. Generic types
don't have covariance.

The reason for this is simple. Consider if DoSomethingElse did:

objects.Add (new object());

You've just passed in an IList<Special>... what should happen? A
runtime exception? One of the points of generics is to give compile-
time type safety, avoiding runtime exceptions due to type issues.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top