I have an object
which may be boxed from int
, float
, decimal
, DateTime
, TimeSpan
etc.
Now I want to convert it to a string
with a format string, such as "D4"
, "P2"
, or "yyyyMMdd"
. But the object
class doesn't have a ToString
method which receives the format string. So the following code doesn't work.
string Format(object value, string format)
{
return value.ToString(format); // error
}
Below is my ugly workaround.
string Format(object value, string format)
{
if (value is int) return ((int)value).ToString(format);
if (value is float) return ((float)value).ToString(format);
if (value is double) return ((double)value).ToString(format);
if (value is decimal) return ((decimal)value).ToString(format);
if (value is DateTime) return ((DateTime)value).ToString(format);
if (value is TimeSpan) return ((TimeSpan)value).ToString(format);
...
}
Is there a smarter way?