Generics resolution in .NET

I recently posted about generics and resolution at runtime. Some people on StackOverflow gave some really good answers – but before I got any responses, and with other people in the office stumped as to this problem, I decided to ask Eric Lippert directly (he of Fabulous Adventures in Coding) to get the definitive answer. Sure enough within a couple of days (by which time a couple of people had posted on SO) I received the following, which crystallised the thoughts of both people on SO plus what I had suspected would be the case…

Indeed, the answers on SO are correct. Generic calls are resolved by the compiler at compile time, using the information available at compile time to make the best choice available at that time. This is exactly the same as if you’d said:
void Foo(string s) {}
void Foo(int x) {}
void Foo(object x) {}

object[] objects = { 10, "hello", null };
We don’t re-do the overload resolution analysis at runtime. The best choice at compile time is the "object" overload, so that’s the one you get every time, no matter what the runtime value is.  It’s no different with generics; we make the best choice we can based on the information you give us at compile time.
If you want to do the analysis at runtime then you can use "dynamic" in C# 4, but be aware that doing full analysis at runtime * does full analysis at runtime*, unsurprisingly. You are basically *starting the compiler again at runtime*.  That’s not cheap. And if the result can change on every call, then of course we re-run the semantic analyzer again on every call.

I wrote a blog article about this a few months back.

So, there’s the answer straight from the horses mouth, as it were. And thanks Eric for your quick and succinct response – really appreciated! I actually looked on Eric’s blog because I thought he had posted something about it – but couldn’t find the above article whilst trawling through his blog – he’s too prolific a blogger!

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s