I have class Customer and I need to make different formats without changing Customer class. I created CustomerFormatProvider for this. BUT when Customer.Format() calls, it ignores CustomFormatProvider.Format. Why ??? Please help!!!!
public class Customer
{
private string name;
private decimal revenue;
private string contactPhone;
public string Name { get; set; }
public decimal Revenue { get; set; }
public string ContactPhone { get; set; }
public string Format(string format)
{
CustomerFormatProvider formatProvider = new CustomerFormatProvider();
return string.Format(formatProvider, format, this);
}
}
public class CustomerFormatProvider : ICustomFormatter, IFormatProvider
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
return this;
return null;
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
Customer customer = (Customer) arg;
StringBuilder str = new StringBuilder();
str.Append("Customer record:");
if (format.Contains("N"))
{
str.Append(" " + customer.Name);
}
if (format.Contains("R"))
{
str.Append($"{customer.Revenue:C}");
}
if (format.Contains("C"))
{
str.Append(" " + customer.ContactPhone);
}
return str.ToString();
}
}
I'd guess the issue is in how you're calling the
Formatmethod. Either of the following will work:or even
You should probably handle default formatting within the
Formatmethod as well.