nirpi
nirpi

Reputation: 715

Pass inherited Interface to a method

I'm having the following interfaces:

public interface IBase
{
    int id1 { get; set; }
}

public interface IDerived : IBase
{
    int id2 { get; set; }
}

And the following (sample) program:

class Program
{
    static void Main(string[] args)
    {
        IList<IDerived> derived = null;
        Check(derived);
    }

    static void Check(IList<IBase> base)
    {
    }
}

I'm getting this compliation error: cannot convert from 'System.Collections.Generic.IList<IDerived>' to 'System.Collections.Generic.IList<IBase>'

If I'm trying to pass only one instance, and not a list, it's working, so what am I missing here?

Thanks,

Upvotes: 0

Views: 373

Answers (4)

csharptest.net
csharptest.net

Reputation: 64218

And yet this would work...

    static void Main(string[] args)
    {
        List<IDerived> derived = null;
        Check(derived.ToArray());
    }

    static void Check(IBase[] asdf)
    {
    }

One of several reasons I prefer the raw array [] or IEnumerable<> for interfaces both on arguments and return values. But if you prefer using List/IList you can still do the following:

    static void Main(string[] args)
    {
        IList<IDerived> derived = null;
        Check(derived);
    }

    static void Check<T>(IList<T> asdf) where T : IBase
    {
    }

Upvotes: 0

jrummell
jrummell

Reputation: 43077

You will need to cast the IList items to IBase. Here's an example using Linq extensions:

Check(derived.Cast<IBase>());

Upvotes: 3

recursive
recursive

Reputation: 86084

An instance of IList<IDerived> is not an instance of IList<IBase>. For one thing, you can't call .Add(new ConcreteBase()) on it. (where ConcreteBase implements IBase)

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351516

This is due to a lack of covariance on interfaces types in C# 3, C# 4 will allow you to specify covariance and contravariance on interfaces types.

Unfortunately this is one of those things that just doesn't work the way you think it should in C# 3.

Upvotes: 3

Related Questions