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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With