Posted by: Cirilo Meggiolaro | 11/18/2008

Tip of the day #35 – Generic variance

I was at work last Friday and a friend sent me a message by MSN because he was trying to assign a generic list of strings to a generic list of objects and the C# compiler was not allowing him to perform that.

Generic variance is the name of my friend’s code issue. Anyway, there is a reason why the C# compiler does not allow us to type the following code:

List<string> myTags = new List<string>();
List<object> myObjects = new List<object>();
myObjects = myTags;

The code is not type safe. Once both collections can have read and write operations, how can you ensure that the code will perform correctly in runtime?

Do you have a solution?

A work around for the particular example’s issue you may create a generic method that receives both collections as parameters with a constraint that defines that the first type should be convertible to the second type as the following code:

public static void Add<S, D>(List<S> source, List<D> destination) where S : D
    foreach (S sourceElement in source)

The call to the function above will be similar as the following code:

Add<string, object>(myTags, myObjects);

It’s just a simple example but generic variance is really more complex than that and you may find a few blogs and architects debating about it. Be aware of that this complexity can put your code in a large overhead zone once you need to develop a lot of work around to make your code run.

If you have to do that, I recommend you to revisit your design. If generics provide a really good way to work with strongly typed objects, why do you need to give some steps back?

If you want to check the MSDN explanation about it, click here!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


%d bloggers like this: