7

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?

Shigure
  • 373
  • 4
  • 13
  • Your code doesn't really make sense - all of those types have different applicable format strings but your `Format` method gives the impression that any format string can be arbitrarily applied to any object (which is obviously not the case). Seems to me you need to unbox the object first and then decide what format string to use...? – Ant P Feb 27 '16 at 09:28

1 Answers1

15

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, ...)

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • 1
    @Dai The question was _I have an `object`_, so I can't do what you suggested. – xanatos Feb 18 '19 at 10:13
  • Theere is an example of use? IFormattable formattable = value as IFormattable; <--- that line makes formattable null so throw new ArgumentException("value") is triggered – AndresChica May 09 '22 at 15:51
  • 1
    @AndresChica Your object must implement the `IFormattable` interface. If you can't cast it to `IFormattable` it means that it doesn't implement it. – xanatos May 09 '22 at 15:58