Overloading null ambiguity

后端 未结 2 1595
[愿得一人]
[愿得一人] 2020-12-20 17:21

I have the following methods:

  void Method(string param1, string param2);
  void Method(string param1, object param2);

When I call the met

相关标签:
2条回答
  • 2020-12-20 17:35

    The problem is that both string and object are nullable, so null could refer to either overload of the method. You have to cast the null value—as stupid as that sounds—to say explicitely which overload you want to call.

    method("string", (string) null);
    method("string", (object) null);
    

    This is basically the same as if you defined a variable of either type and passed that then:

    string param1 = null;
    object param2 = null;
    
    method("string", param1); // will call the string overload
    method("string", param2); // will call the object overload
    

    Both param1 and param2 have the same value, null, but the variables are of different types which is why the compiler is able to tell exactly which overload it needs to use. The solution above with the explicit cast is just the same; it annotates a type to the null value which is then used to infer the correct overload—just without having to declare a variable.

    0 讨论(0)
  • 2020-12-20 17:45

    You can be specific about which version of the method you want to call by specifying which type of null you're passing:

    Method("string", null as string);
    
    0 讨论(0)
提交回复
热议问题