4

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

I am trying to understand why the base types do not have the method implementations even though they implements IConvertible interface. Could anyone please help on this?

Raji
  • 59
  • 3
  • 1
    Explicit interface implementation methods require BindingFlags.NonPublic to be found. They are private. – Hans Passant Nov 24 '14 at 00:31
  • "Metadata of these types do not contain..." is very strange claim, especially without mentioning tools you've used/code you've tried. Assuming you've read [System.Int32](http://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx) documentation better (also likely duplicate) question should be "how to get metadata on explicitly implemented interfaces for `Int32`, my code ... does not show any methods". – Alexei Levenkov Nov 24 '14 at 00:36

2 Answers2

8

Take a closer look at the documentation - Int32 implements IConvertible explicitly.

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

var asConvertable = (IConvertible) 3; //boxing
var someByte = asConvertible.ToByte();
dcastro
  • 66,540
  • 21
  • 145
  • 155
  • Thank you dcastro for pointing that Int32 implements IConvertible explicitly. I understand it now. Thanks. – Raji Nov 25 '14 at 12:30
  • This was a lifesaver while building a netstandard library that targeted both netstandard and framework. Apparently it's explicit in netstandard versions, but not in framework (or so says my compiler). – gregsdennis Jun 26 '17 at 08:06
3

Int32 and other primitive types implement the IConvertible interface explicitly. Explicit interface implementation means that the method doesn't appear in the concrete's type public methods: you can't call it directly, you need to cast to the interface first.

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

To implement an interface explicitly, you don't specify an accessibility level, and you prefix the method name with the interface name:

byte IConvertible.ToByte()
{
    ...
}

To access the method with reflection, you must include the full name of the interface:

MethodInfo toByte =
    typeof(int).GetMethod("System.IConvertible.ToByte",
                          BindingFlags.Instance | BindingFlags.NonPublic);
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758