I occasionally find that the class System.String
of the .NET framework does not implement its inherited interface System.IConvertible
, why, please?
What you're witnessing is something called "explicit interface implementation". What this means is that if you define a class (in this case System.String
) and implement an interface (in this case System.IConvertible
) and you implement it using explicit interface syntax, i.e.
This:
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(this, provider);
}
Vs.
public bool ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(this, provider);
}
Then the method ToBoolean
will not be accessible if the compile-time-type of the target of the method is actually an instance of your type, rather than the interface. This is really a way for API writers in C# to "hide" certain members that, though for various reasons must be implemented by the implementing type, are not really intended to be part of the public surface area of your type. It's actually pretty nice, as it allows you to make your API cleaner than it might otherwise have been.
In this case, the reason one might consider it cleaner to prevent consumers from interacting with string
as a simple IConverter
is that the whole point of System.Convert
is to allow converting values of types such as string
into types such as bool
by using these methods. Therefore, providing the interface-methods as a way to do the same thing that System.Convert
already does would only confuse the API by providing uselessly additional ways to accomplish the same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With