Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to tell if an object is awaitable at runtime?

Tags:

c#

async-await

I recently learned that any object with a GetAwaiter method returning an awaiter can be await-ed. This is true even if it's an extension method, meaning basically any object can be made await-able, if you so choose.

But is there a way to tell at runtime if an object is await-able? Normal reflection won't work, since it doesn't list an object's extension methods.

I don't have a particular need in mind when asking this question, I'm just curious if it's possible.

like image 537
BlueRaja - Danny Pflughoeft Avatar asked Sep 01 '15 21:09

BlueRaja - Danny Pflughoeft


1 Answers

It's not possible because the information that the C# compiler uses to make that decision is gone.

In order to resolve extension methods we need to know the namespaces that are imported. That information is not available at runtime. It is a C#-only concept. The CLR does not know what a using is.

I cannot think of any reason you would want to see if an object is possibly awaitable at runtime because you can't act on that information. Maybe you could check if the object is a Task instead?

like image 51
usr Avatar answered Oct 05 '22 12:10

usr