How does the IConvertible interface work with DataRow?

I'm just wondering how the Convert and IConvertible interface works with DataRow . If I have this code:

 string s="25"; int x= Convert.ToInt32(s); 

When Convert.ToInt32(s) is called Convert.ToInt32(s) following will be executed:

 ((IConvertible)s).ToInt32() 

So, how does this work with such a line of code:

 Convert.ToInt32(myDataRow["intField"]); 

When neither DataRow nor object are implemented IConvertible?

+4
source share
1 answer

The DataRow fields are displayed as objects, so the call is made in 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 convert from object to IConvertible . It does not matter that object does not implement the interface; what matters is that any actual concrete type in the DataRow at runtime must implement an interface. All built-in CLR base types implement IConvertible , for example, so it will call String.ToInt32() or Boolean.ToInt32() or whatever. Interfaces are implemented explicitly, so you cannot directly access these methods on your own with string or bool , but you can raise the totals 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 this method on an object that does not implement IConvertible, you will get an exception when creating the script:

 var o = new object(); var x2 = Convert.ToInt32(o); // throws System.InvalidCastException: "Unable to cast object of type 'System.Object' to type 'System.IConvertible'." 
+7
source

Source: https://habr.com/ru/post/1393768/


All Articles