I'm just wondering how the Convert
class and IConvertible
interface works with a DataRow
. If I have this code:
string s="25";
int x= Convert.ToInt32(s);
The call to Convert.ToInt32(s)
will run the following:
((IConvertible)s).ToInt32()
So how does this work with a line of code like this:
Convert.ToInt32(myDataRow["intField"]);
When neither DataRow nor object implement IConvertible?
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:The runtime attempts to perform a conversion from
object
toIConvertible
. It doesn't matter thatobject
doesn't implement the interface; what matters is that whatever actual, concrete type is in theDataRow
at runtime has to implement the interface. All of the built-in CLR base types implementIConvertible
, for example, so it will callString.ToInt32()
orBoolean.ToInt32()
or whatever. The interfaces are implemented explicitly, so you can't call those methods directly on your ownstring
orbool
, but you could upcast toIConvertible
and do it.If you try to run that method on an object that doesn't implement IConvertible, you'll get a runtime typecast exception: