Note that there are some explanatory texts on larger screens.

plurals
  1. POMethod resolution in extension methods with optional parameters
    text
    copied!<p>I have the following couple of extension methods, which are in the same namespace and assembly:</p> <pre><code>public static class DateTimeExtensions { public static string NullSafeToString(this DateTime? possiblyNullDateTime, string format, string nullString = "") } public static class NullableExtensions { public static string NullSafeToString&lt;T&gt;(this Nullable&lt;T&gt; nullable, string nullString = "") where T : struct } </code></pre> <p>My question is about method resolution. The following call (from another namespace) resolves to <code>ObjectExtensions.NullSafeToString</code> when I expected <code>DateTimeExtensions.NullSafeToString</code>:</p> <pre><code>DateTime? dateTime; // ... dateTime.NullSafeToString("yyyyMMdd"); </code></pre> <p>Removing the optional parameter from <code>DateTimeExtensions.NullSafeToString</code> causes it to resolve as expected.</p> <p>Section 7.6.5.2 of the C# spec outlines the order of the namespaces searched, but because the above are in the same namespace, I'd expect it to use the rules in section 7.6.5.1.</p> <p>I thought it'd match <code>DateTimeExtensions.NullSafeToString</code> because:</p> <ul> <li>Although they'll both have a first parameter type of <code>Nullable&lt;DateTime&gt;</code>, I thought a non-generic method (i.e. without the type parameter) would be considered first.</li> <li>I though the parameter lists would be considered without their optional parameters first</li> </ul> <p>Can anyone clarify why it's picking <code>ObjectExtensions.NullSafeToString</code> over <code>DateTimeExtensions.NullSafeToString</code>?</p> <p>(Aside: From other discussions on here, I suspect some people may disapprove of using extension method semantics to make dereferencing null-safe, but I find that used for limited scenarios like this, they make for more readable code. Also I know <code>Nullable.ToString</code> is already null-safe because the <code>Nullable</code> object itself isn't null, but that doesn't cater for parameters to the contained <code>ToString</code>, and I find that the explicitly named method indicates the null-safe intent.)</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