John Lam 1997 — 2026

Covariance in the CLR

While writing my first real Ruby app using my bridge, I came across my first real honest-go-goodness nasty bug. Most of the other bugs have been nice and deterministic – something I just did caused the bridge to blow up. This one was just plain nasty, and of course it was based on an invalid assumption. It manifested itself as a corrupted call stack and dumped me rather unceramoniously into the debugger.

Here’s the invalid assumption: I thought that there wasn’t return-value covariance in C# (the CLR supports return-value covariance, but I thought this was a safe assumption since I figured most folks wouldn’t be writing code using ilasm).

For example, you cannot have these two methods in the same type:

int Method() and string Method()

However, if they can be distinguished based on their parameter lists, then it’s OK:

int Method(int) and string Method(string)

I had made the assumption in my overload shim that all overloads would return the same type. Oops. I ran into this bug when I was calling ToolStripItemCollection.Add.

What’s worse, the MSDN docs essentially imply that all of the return values are the same since the return values of the methods aren’t shown in the overloads list. I only noticed this when I pulled out Reflector to look at the methods myself.

I’m really happy that this was the root cause of the stack corruption bug. I was worried that there was something flaky about the interactions between the garbage collectors on both sides of the marshaling boundary …

3 archived reader comments

John Lam (2006/02/19)

Jamie, thanks for that pointer. Do you have an example handy for where these conversion operators are used in the libraries?

Rob Loach (2006/02/19)

You’ve made a lot of progress on this bridge, John. Way to go!

Omer van Kloeten (2006/02/24)

The way methods are overloaded is the same in C# as it is in classic C. It’s pretty logical, given that you can’t, either implicitly or explicitly request a certain return type. Let’s take an example of class A and class B, both of which have a method named Foo. Class B inherits class A. Let’s take another two classes - RetP and RetD when RetD derives from RetP. Return type covariance means that if class A’s Foo returns RetP, class B’s Foo could return RetD and not be required to return RetP. This, in contrast to your statement that return type covariance could be about string and int. I have a post about it here, if you like: http://weblogs.asp.net/okloeten/archive/2004/04/24/119580.aspx