Interesting Interfaces Series – IConvertible

So after my little discovery of IEnumerable on the string type I thought I’d see what other interesting interfaces I’ve missed, and I thought I’d start off with the interfaces that exist on the .NET primitive types. First off, IConvertible.

The .NET documentation describes IConvertible as “Defines methods that convert the value of the implementing reference or value type to a common language runtime type that has an equivalent value”; basically it’s an interface that exposes methods to convert the implementing type so all the available .NET primitive types. This interface is implemented by all the .NET primitive types, i.e. string, int, bool, etc.

The IConvertible interface consists of the following:

  • bool ToBoolean(IFormatProvider provider);
  • byte ToByte(IFormatProvider provider);
  • char ToChar(IFormatProvider provider);
  • DateTime ToDateTime(IFormatProvider provider);
  • decimal ToDecimal(IFormatProvider provider);
  • double ToDouble(IFormatProvider provider);
  • short ToInt16(IFormatProvider provider);
  • int ToInt32(IFormatProvider provider);
  • long ToInt64(IFormatProvider provider);
  • sbyte ToSByte(IFormatProvider provider);
  • float ToSingle(IFormatProvider provider);
  • string ToString(IFormatProvider provider);
  • object ToType(Type conversionType, IFormatProvider provider);
  • ushort ToUInt16(IFormatProvider provider);
  • uint ToUInt32(IFormatProvider provider);
  • ulong ToUInt64(IFormatProvider provider);

Now you’re probably think but hey I’ve never seen ToInt32() as a method on a string, and you’d be right. It is there, it just isn’t exposed, the method ToInt32 is not public but it is explicitly defined for the interface so you can only get to the method if you cast string to IConvertible. So doing the following would give you an int with the value of 123:


string input = "123";
int output = ((IConvertible)input).ToInt32(null);

All that String.ToInt32() is doing in the background is calling System.Convert.ToInt32():


int IConvertible.ToInt32(IFormatProvider provider)
{
    return Convert.ToInt32(this, provider);
}

Which it turn calls int.Parse():


public static int ToInt32(string value, IFormatProvider provider)
{
    if (value == null)
    {
        return 0;
    }

    return int.Parse(value, NumberStyles.Integer, provider);
}

Anyway, I hope that’s useful for you.