Nenad Dobrilovic
Nenad Dobrilovic

Reputation: 1555

Does Convert.ChangeType call ToString() internally?

Is there any difference between:

value.ToString()

and

(string)Convert.ChangeType(value, typeof(string))

Upvotes: 0

Views: 354

Answers (2)

Konstantin Oznobihin
Konstantin Oznobihin

Reputation: 5327

when target type is string, Convert.ChangeType works like this:


if (value == null)
{
    return null;
}

var convertible = value as IConvertible;
if (convertible == null)
{
    throw new InvalidCastException();
}

return convertible.ToString();

so it's quite different from value.ToString();

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190952

It calls the IConvertable.ToString after ensuring the types are IConvertable.

case TypeCode.String:
   return (object) convertible.ToString(provider);

So as a result, its doing a lot more work just to call ToString with an IFormatProvider. It will all depend on the implementation of the type that implements IConvertable.

The provider comes from (IFormatProvider) Thread.CurrentThread.CurrentCulture.

This is what int does.

public override string ToString()
{
  return Number.FormatInt32(this, (string) null, NumberFormatInfo.CurrentInfo);
}

public string ToString(string format)
{
  return Number.FormatInt32(this, format, NumberFormatInfo.CurrentInfo);
}

public string ToString(IFormatProvider provider)
{
  return Number.FormatInt32(this, (string) null, NumberFormatInfo.GetInstance(provider));
}

public string ToString(string format, IFormatProvider provider)
{
  return Number.FormatInt32(this, format, NumberFormatInfo.GetInstance(provider));
}

Upvotes: 3

Related Questions