Tuesday, June 05, 2007

Covariance

Last night I tripped on something that after a little bit of Googling, I discovered was quite a trap for young players in the OOP / C# development arena...covariance.

This occurs when you build a nice little hierarchy of objects, with a base and several child objects then try to introduce Generics into the equation.

So I have a BaseEntity, and a class that exposes a collection of BaseEntity thusly;

public List MyList
{
... etc...
}

then, you try to cast a List set up like this...

private List myChildList = goGetAChildList();

It doesn't compile.

This is because casting the List, is not like casting the individual objects.

The point of this really hit home when it was described is that, if casting in this way was allowed, you could add objects of all different but inherited types, to your Base List.

Anyway, this post isn't meant to comprehensively explain the issue of co-variance, justremind me that it exists, and point me on to here...

No comments:

Post a Comment