Why does C#/Framework allow me to use an optional parameter to create an overload that it otherwise does not allow?
public static TOut? NullableConvert<TOut>(object source, Func<object, TOut> converter) where TOut : struct
{
}
public static TOut NullableConvert<TOut>(object source, Func<object, TOut> converter) where TOut : class
{
}
When I try above overloads I get the following error which I agree with:
Error CS0111 Type 'DataHelpers' already defines a member called 'NullableConvert' with the same parameter types
However, if I add an optional parameter to one of the methods as shown below then I am allowed to use these overloads (please note object x = null
).
public static TOut? NullableConvert<TOut>(object source, Func<object, TOut> converter) where TOut : struct
{
}
public static TOut NullableConvert<TOut>(object source, Func<object, TOut> converter, object x = null) where TOut : class
{
}
When I run following the run time resolves correct overloads without the optional parameter
long? x = DataHelpers.NullableConvert(DBNull.Value, Convert.ToInt64);
string y = DataHelpers.NullableConvert(DBNull.Value, Convert.ToString);
How are the compiler/runtime able to resolve the overload without the optional parameter?
Why did I get the error at the first place if the methods could be resolved?