Why does Convert.ChangeType accept an object parameter?

The class Convertexists since .NET 1.0. An interface IConvertiblealso exists from now on.

The method Convert.ChangeTypeonly works with type objects that implement IConvertible(in fact, if I'm not mistaken, all the conversion methods provided by the class Convertin this way). So why parameter type object?

In other words, instead:

public object ChangeType(object value, Type conversionType);

Why is this not a signature?

public object ChangeType(IConvertible value, Type conversionType);

It just seems strange to me.

+5
source share
1 answer

Looking into the reflector, you can see the top ChangeType(object, Type, IFormatProvider), which is called under the cover:

public static object ChangeType(object value, Type conversionType, IFormatProvider provider)
{
  //a few null checks...
  IConvertible convertible = value as IConvertible;
  if (convertible == null)
  {
    if (value.GetType() != conversionType)
    {
        throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
    }
    return value;
  }

, , IConvertible, , .

, , , IConvertible, object.


LinqPad :

void Main()
{
  var t = new Test();
  var u = Convert.ChangeType(t, typeof(Test));
  (u is IConvertible).Dump();   //false, for demonstration only
  u.Dump();                     //dump of a value Test object
}

public class Test {
  public string Bob;
}
+5

All Articles