Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It depends on <code>TypeA</code> and <code>TypeB</code>.</p> <ul> <li>If exactly one of them is applicable (e.g. there is no conversion from <code>null</code> to <code>TypeB</code> because it's a value type but <code>TypeA</code> is a reference type) then the call will be made to the applicable one.</li> <li>Otherwise it depends on the relationship between <code>TypeA</code> and <code>TypeB</code>. <ul> <li>If there is an implicit conversion from <code>TypeA</code> to <code>TypeB</code> but no implicit conversion from <code>TypeB</code> to <code>TypeA</code> then the overload using <code>TypeA</code> will be used.</li> <li>If there is an implicit conversion from <code>TypeB</code> to <code>TypeA</code> but no implicit conversion from <code>TypeA</code> to <code>TypeB</code> then the overload using <code>TypeB</code> will be used.</li> <li>Otherwise, the call is ambiguous and will fail to compile.</li> </ul></li> </ul> <p>See section 7.4.3.4 of the C# 3.0 spec for the detailed rules.</p> <p>Here's an example of it not being ambiguous. Here <code>TypeB</code> derives from <code>TypeA</code>, which means there's an implicit conversion from <code>TypeB</code> to <code>TypeA</code>, but not vice versa. Thus the overload using <code>TypeB</code> is used:</p> <pre><code>using System; class TypeA {} class TypeB : TypeA {} class Program { static void Foo(TypeA x) { Console.WriteLine("Foo(TypeA)"); } static void Foo(TypeB x) { Console.WriteLine("Foo(TypeB)"); } static void Main() { Foo(null); // Prints Foo(TypeB) } } </code></pre> <p>In general, even in the face of an otherwise-ambiguous call, to ensure that a particular overload is used, just cast:</p> <pre><code>Foo((TypeA) null); </code></pre> <p>or</p> <pre><code>Foo((TypeB) null); </code></pre> <p>Note that if this involves inheritance in the declaring classes (i.e. one class is overloading a method declared by its base class) you're into a whole other problem, and you need to cast the target of the method rather than the argument.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload