I would like to write a ToString() method for a generic class where I can specify a StringFormat.
So far, I have the following code:
public class Foo<T> : IFoo
{
public T Value { get; set; }
string IFoo.Value { get { ValueToString(Value); } }
public string StringFormat { get; set }
public Foo(T value, string stringFormat)
{
Value = value;
StringFormat = stringFormat;
}
private string ValueToString(T value)
{
if (!string.IsNullOrEmpty(StringFormat))
{
var formattable = value as IFormattable;
if (formattable != null)
{
var format = CultureInfo.CurrentCulture.GetFormat(typeof(T)) as IFormatProvider;
if (format != null)
return formattable.ToString(StringFormat, format);
}
}
return Convert.ToString(value);
}
}
public interface IFoo
{
string Value { get; }
}
I am calling the code like this:
public class Bar
{
public Bar()
{
var dateTimeFoo = new Foo<DateTime>(DateTime.Now, "dd.MM.yyyy");
var iFoo = dateTimeFoo as IFoo;
if (Convert.ToString(dateTimeFoo.Value) != iFoo.Value)
{
//stringformat worked...
}
}
}
The problem with my current implementation is this line of code:
var format = CultureInfo.CurrentCulture.GetFormat(typeof(T)) as IFormatProvider;
It returns null and it should return null for objects that don't have a FormatProvider but DateTime certainly has the ability, how can I get the correct FormatProvider of a generic T?
CultureInfo already implements IFormatProvider, all you want to do is
return formattable.ToString(StringFormat, CulturuInfo.CurrentCulture);
If you look at the implementation of GetFormat method
public virtual Object GetFormat(Type formatType)
{
if (formatType == typeof (NumberFormatInfo))
{
return (NumberFormat);
}
if (formatType == typeof (DateTimeFormatInfo))
{
return (DateTimeFormat);
}
return (null);
}
You can see it only supports two types and returns null otherwise as documented here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With