Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an object to a string with a format string? [duplicate]

Tags:

c#

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?

like image 534
Shigure Avatar asked Feb 27 '16 09:02

Shigure


People also ask

How do you turn an object into a string?

Stringify a JavaScript ObjectUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

How do you convert an object to a string in Python?

Converting Object to String Everything is an object in Python. So all the built-in objects can be converted to strings using the str() and repr() methods.

How do I format a string in C#?

The most common way how we format strings is by using string. Format() . In C#, the string Format method is used to insert the value of the variable or an object or expression into another string.


1 Answers

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

like image 98
xanatos Avatar answered Sep 20 '22 22:09

xanatos