Reputation: 1388
i have a generally question about the conversion method ".ToString()". At first i use this statement for the conversion:
Nullable<int> SomeProperty;
string test = SomeProperty.ToString();
Up to here there is no problem but after that i want to add "CultureInfo.InvariantCulture" to the ToString() method. It doesn't work because the .ToString() of a Nullable has no parameters. Why does Resharper suggest to insert the CultureInfo informations to me??
After that i try a other way and use this statement:
Nullable<int> SomeProperty;
string test = Convert.ToString(SomeProperty, CultureInfo.InvariantCulture);
This statement works fine but now i want to understand the technical difference between the first and the second statement??
Upvotes: 2
Views: 643
Reputation: 125630
Convert.ToString Method (Object, IFormatProvider):
If the value parameter implements the IConvertible interface, the method calls the IConvertible.ToString(IFormatProvider) implementation of value. Otherwise, if the value parameter implements the IFormattable interface, the method calls its IFormattable.ToString(String, IFormatProvider) implementation. If value implements neither interface, the method calls the value parameter's ToString() method.
Nullable<int>
is seen like standard int
, and IFormattable.ToString(String, IFormatProvider)
is fired when Convert.ToString
with format provider is called.
Proof:
class MyFormatProvider : IFormatProvider
{
public object GetFormat(Type formatType)
{
return "G";
}
}
static void Main(string[] args)
{
Nullable<int> SomeProperty = 1000000;
Console.WriteLine(SomeProperty.ToString());
Console.WriteLine(Convert.ToString(SomeProperty));
Console.WriteLine(Convert.ToString(SomeProperty, new MyFormatProvider()));
}
Put breakpoint within GetFormat
and it's going to be hit when the last one of Main
is executed.
Upvotes: 4
Reputation: 3261
read msdn http://msdn.microsoft.com/en-us/library/6t7dwaa5.aspx
The return value is formatted with the general numeric format specifier ("G") and the NumberFormatInfo object for the current culture.
Upvotes: 0