Method resolution in extension methods with optional parameters

I have the following several extension methods that are in the same namespace and assembly:

public static class DateTimeExtensions
{
    public static string NullSafeToString(this DateTime? possiblyNullDateTime, string format, string nullString = "")
}

public static class NullableExtensions
{
    public static string NullSafeToString<T>(this Nullable<T> nullable, string nullString = "") where T : struct
}

My question is about method resolution. The following call (from another namespace) resolves ObjectExtensions.NullSafeToStringwhen I expected DateTimeExtensions.NullSafeToString:

DateTime? dateTime;
// ...
dateTime.NullSafeToString("yyyyMMdd");

Removing an optional parameter from DateTimeExtensions.NullSafeToStringresults in its resolution as expected.

Section 7.6.5.2 of the C # specification describes how to search for namespaces, but since the above are in the same namespace, I expect it to use the rules in section 7.6.5.1.

I thought it would fit DateTimeExtensions.NullSafeToString, because:

  • Nullable<DateTime>, , (.. ).
  • ,

- , ObjectExtensions.NullSafeToString DateTimeExtensions.NullSafeToString?

( : , , , , , , . Nullable.ToString , Nullable , ToString, , .)

+5
1

. . (7.5.3 # spec)

public static string NullSafeToString(DateTime? possiblyNullDateTime, string format, string nullString = "")
    {
        return string.Empty;
    }
    public static string NullSafeToString<T>(Nullable<T> nullable, string nullString = "") where T : struct
    {
        return string.Empty;
    }
    static void Test()
    {
        DateTime? datetime = DateTime.Now;
        NullSafeToString(datetime, "yyyyMMdd");
    }
+1
source

All Articles