Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide compile-time constant for IFormatProvider

Tags:

c#

.net

I'm trying to create a string extension method with the following signature:

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

I'm getting a compiler error:

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

Couldn't find anything on google and my only work around is to do this:

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

Anyone know how I can set the default value of IFormatProvider in the signature? Is it even possible? IFormatProvider is an interface so I'm assuming that's where the issue lies.

like image 783
John Paul Avatar asked Nov 30 '15 15:11

John Paul


2 Answers

how I can set the default value of IFormatProvider in the signature? Is it even possible?

No. Optional arguments ("default parameters") are a modification of the language, introduced with C# 4.0 and Visual Studio 2010.

Providing a default value for a parameter does not change that method signature. In your case, there is only one method signature:

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

And in the metadata of that method, so in the compiled assembly, the default values will be recorded. Any caller that wishes to use these default values, will get those from the metadata - and compile their values into the call site.

Because that is how it works, the default values must be compile-time constants, so they can be embedded in the metadata.

DateTimeFormatInfo.CurrentInfo is not a compile-time constant, it is an object instance set by the runtime.

like image 147
CodeCaster Avatar answered Sep 25 '22 00:09

CodeCaster


In this case i advice to create several overloaded methods, and in one with less parameters set defaults inside and call another with more parameters:

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);
}
like image 24
Backs Avatar answered Sep 23 '22 00:09

Backs