I am trying to write a C# generic method that accepts nullable decimal and double values and converts them to a string representation.
I am getting the error "No overload for method 'ToString' takes 1 arguments" although I am accessing .Value of the nullable parameter.
Here is my code. What am I doing wrong?
public static string ToThousandSeparated<T>(T? value, string naString = "") where T : struct
{
if (value.HasValue)
{
T val = value.Value;
return val.ToString("N0");
}
return naString;
}
objectonly defines the methodstring ToString()(with no parameters). Objects likeInt32define their ownstring ToString(string)method.However, there's a useful interface called
IFormattable, which provides astring ToString(string, IFormatProvider)method. So you can either constrain yourself to allTwhich implementIFormattable:or accept anything, but test whether it implements
IFormattableat runtime: