Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using covariance outside the context of IEnumerable<T> [duplicate]

Possible Duplicate:
Does C# support return type covariance?
Why can’t I implement an Interface this way?

Consider the following:

public interface IAnimal {
}

public class Animal : IAnimal {
}

public interface ICage {
     IAnimal SomeAnimal {get;}
}

public class Cage : ICage{
     public Animal SomeAnimal { get; set; }
}

I've read a lot of stuff on covariance and contravariance for IEnumerable, but I'm not sure how to get the above code to work. I get the error "Cage does not implement interface member IAnimal". Since it defined Animal, which is more defined than IAnimal, it seems like covariance should take care of me.

What am I missing? Thanks in advance.

like image 566
reustmd Avatar asked Dec 15 '22 15:12

reustmd


1 Answers

That's not currently possible in C#.

It theoretically possible for the language designers to add it, they just haven't [yet]. They may or may not decide to add it to a potential future version of C#.

The best workaround would probably be:

public class Cage : ICage
{
    public Animal SomeAnimal { get; set; }

    IAnimal ICage.SomeAnimal
    {
        get { return SomeAnimal }
    }
}
like image 72
Servy Avatar answered Apr 23 '23 19:04

Servy