The DataRow fields are exposed as objects, so the call is made to Convert.ToInt32(object value)
, which does exactly what you said in your question:
return value == null? 0: ((IConvertible)value).ToInt32(null);
The runtime attempts to perform a conversion from object
to IConvertible
. It doesn't matter that object
doesn't implement the interface; what matters is that whatever actual, concrete type is in the DataRow
at runtime has to implement the interface. All of the built-in CLR base types implement IConvertible
, for example, so it will call String.ToInt32()
or Boolean.ToInt32()
or whatever. The interfaces are implemented explicitly, so you can't call those methods directly on your own string
or bool
, but you could upcast to IConvertible
and do it.
object s = new System.String('1', 3);
var i = Convert.ToInt32(s);
// s = "111"; i = 111
If you try to run that method on an object that doesn't implement IConvertible, you'll get a runtime typecast exception:
var o = new object();
var x2 = Convert.ToInt32(o);
// throws System.InvalidCastException: "Unable to cast object of type 'System.Object' to type 'System.IConvertible'."