Why don't the .Net Framework base types contain implementations of IConvertible methods?

... Basic Net Framework base types like Int32, Int64, Boolean, etc. implement the IConvertible interface, but the metadata of these types does not contain implementations of the methods defined in the IConvertible interface, such as ToByte, ToBoolean, etc.

I'm trying to figure out why base types don't have a method implementation, even though they do implement the IConvertible interface. Can anyone help with this?

+3


source to share


2 answers


Take a closer look at the documentation - it Int32

implements it IConvertible

explicitly .

When a class / struct implements an interface explicitly, you need to expose instances of that type to its interface before calling those methods



var asConvertable = (IConvertible) 3; //boxing
var someByte = asConvertible.ToByte();

      

+7


source


Int32

and other primitive types implement the interface IConvertible

explicitly . Explicitly implementing an interface means that the method does not appear in public methods of a particular type: you cannot call it directly, you need to pass it to the interface first.

int x = 42;
IConvertible c = (IConvertible)x;
byte b = c.ToByte();

      

To implement an interface explicitly, you do not specify the accessibility level and prefix the method name with the interface name:



byte IConvertible.ToByte()
{
    ...
}

      

To access a method with reflection, you must provide the fully qualified interface name:

MethodInfo toByte =
    typeof(int).GetMethod("System.IConvertible.ToByte",
                          BindingFlags.Instance | BindingFlags.NonPublic);

      

+2


source







All Articles