mahmood
mahmood

Reputation: 117

Cast generic List to implemented interfaces C#

I want to filter a list inside a class that implemented some interface.

Here is my codes:

public interface IChild
{
    public string Nth { get; set; }
}
public interface IChild<T> : IChild
{
    public T Parent { get; set; }
}
public class TeacherChilren : IChild<Teacher>
{
    public Teacher Parent { get; set; }
    public string Nth { get; set; }
}
public interface Parent
{
    public string Name { get; set; }
}
public interface ChildOwner<T> : Parent where T : IChild
{
    public List<T> Children { get; set; }
}
public class Teacher : ChildOwner<TeacherChilren>
{
    public string Name { get; set; }
    public List<TeacherChilren> Children { get; set; }
}
var list = new List<Teacher>{
    new Teacher()
};
Console.WriteLine(new Teacher() is ChildOwner<IChild>);
Console.WriteLine(list is List<ChildOwner<IChild>>);

I want to cast the list but the output is false.

Why output is false?

My design is wrong?

what is the solution?

Upvotes: 1

Views: 93

Answers (1)

StepUp
StepUp

Reputation: 38134

If you want to cast ChildOwner to Teacher, then it is not eligible.

Let me show an example:

public class Vehicle 
{

}

public class Plane : Vehicle
{
    public PilotWheel PilotWheel { get; set; }
}

Vehicle cannot be cast to Plane type. Because where we can take PilotWheel value? However, Plane can be casted to Vehicle type.

UPDATE:

I want to cast teacher to childowner not opposite.

It is illegal too. Let's see this example:

class Animal { }

class Sheep : Animal { }

class Wolf : Animal { }

and:

List<Sheep> sheep = new List<Sheep>();
List<Animal> animals = (List<Animal>)sheep; // illegal

Why is the cast illegal?

Let's suppose it was legal. Now we add another line:

animals.Add(new Wolf());

So it would be disaster if casting will work

Read more here about Covariance and contravariance in generics

UPDATE 1

For list is reasonable but why cant cast teacher to chilowner?

You can. Let me show an example:

Teacher teacher = new Teacher();
ChildOwner<TeacherChilren> foo = teacher;

Upvotes: 2

Related Questions