c# - Is it an expected behavior in overloading resolution? -


let's have following simplified code:

update: methods returns object generic type <t>.

void main() {     foo<object>(null); }  bar<t> foo<t>(t value) // first {     console.writeline("value: {0}", value);     // return new bar<t> ... }  async void foo<t>(task<t> task) // second {     console.writeline("value task: {0}", await task);     // return new bar<t> ... } 

this code fails in runtime: object reference not set instance of object. have realized compiler chooses second overload of foo task<t> argument. , therefore fails when trying await null.

maybe correct behavior according c# spec, can cause real troubles, since not right overload programmer wanted. if not bug in specification or in compiler, shouldn't compiled show warning in similar cases? convenient way tell compiler choose first overload?

overloads chosen based on compile time type, not run time type, should work:

void main() {     object value = null;     foo<object>(value); } 

as mentioned in deleted answer, can cast object first:

foo<object>((object)null); 

or

foo<object>(null object); 

Comments