T
Tony Johansson
Hi!
This class Price implements the IFormattable interface below.
When I have this kind of statement
Console.WriteLine("{0:N2}", p);
in main the implemented method ToString from interface IFormattable is
called.
But if I for example just replace this {0:N2} with "test" the method
ToString is not called.
So it seems to me that the compiler in some way check the first argument for
a valid
format. So if a valid format it will call the ToString.
Do I have right in my suggestions ?
class Price : IFormattable
{
double _price;
public Price(double value)
{
this._price = value;
}
public String ToString(String format, IFormatProvider fp)
{
if (format == "$")
{
return "$" + this._price.ToString("0.00");
}
else if (format == null || format.Trim().Equals(""))
{
return this._price.ToString();
}
else
{
return format + " " + this._price.ToString();
}
}
static void Main(string[] args)
{
Price p = new Price(15.5);
Console.WriteLine("{0:N2}", p);
Console.WriteLine(p);
Console.ReadLine();
}
}
//Tony
This class Price implements the IFormattable interface below.
When I have this kind of statement
Console.WriteLine("{0:N2}", p);
in main the implemented method ToString from interface IFormattable is
called.
But if I for example just replace this {0:N2} with "test" the method
ToString is not called.
So it seems to me that the compiler in some way check the first argument for
a valid
format. So if a valid format it will call the ToString.
Do I have right in my suggestions ?
class Price : IFormattable
{
double _price;
public Price(double value)
{
this._price = value;
}
public String ToString(String format, IFormatProvider fp)
{
if (format == "$")
{
return "$" + this._price.ToString("0.00");
}
else if (format == null || format.Trim().Equals(""))
{
return this._price.ToString();
}
else
{
return format + " " + this._price.ToString();
}
}
static void Main(string[] args)
{
Price p = new Price(15.5);
Console.WriteLine("{0:N2}", p);
Console.WriteLine(p);
Console.ReadLine();
}
}
//Tony