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?
There is an interface for that, it is IFormattable
:
public static string Format(object value, string format, IFormatProvider formatProvider = null)
{
if (value == null)
{
return string.Empty;
}
IFormattable formattable = value as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, formatProvider);
}
throw new ArgumentException("value");
}
(this interface is the one used by the various string.Format
, Console.Write
, ...)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments