Provide compile time constant for IFormatProvider

I am trying to create a line extension method with the following signature:

public static DateTime? TryParseExact(this string src, string format, IFormatProvider provider = DateTimeFormatInfo.CurrentInfo, DateTimeStyles style = DateTimeStyles.None)
{
}

I get a compiler error:

The default parameter value for 'provider' must be a compile-time constant

Could not find anything on Google, and my only job is:

public static DateTime? TryParseExact(this string src, string format, IFormatProvider provider = null, DateTimeStyles style = DateTimeStyles.None)
{
    if (provider == null)
        provider = DateTimeFormatInfo.CurrentInfo;
}

Does anyone know how I can set the default for IFormatProvider in a signature? Is it possible? IFormatProvider is an interface, so I guess where the problem is.

+4
source share
2 answers

How can I set the default value for IFormatProvider in the signature? Is it possible?

. ( " " ) , # 4.0 Visual Studio 2010.

. :

TryParseExact(this string src, string format, IFormatProvider provider, DateTimeStyles style);

, . , , - .

, , .

DateTimeFormatInfo.CurrentInfo , , .

+3

, :

public static DateTime? TryParseExact(this string src, string format, IFormatProvider provider, DateTimeStyles style)
{
    //do stuff
}

public static DateTime? TryParseExact(this string src, string format)
{
    IFormatProvider provider = DateTimeFormatInfo.CurrentInfo;
    DateTimeStyles style = DateTimeStyles.None;
    return TryParseExact(src, format, provider, style);
}
+2

Source: https://habr.com/ru/post/1618001/


All Articles