How does the IConvertible interface work with DataRow?

2.7k views Asked by At

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?

1

There are 1 answers

0
Michael Edenfield On BEST ANSWER

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'."