Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.String does not implement the interface System.IConvertible

Tags:

c#

.net

I occasionally find that the class System.String of the .NET framework does not implement its inherited interface System.IConvertible, why, please?

like image 200
Kyle Avatar asked Dec 10 '22 17:12

Kyle


1 Answers

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.

like image 117
Kirk Woll Avatar answered Jun 04 '23 04:06

Kirk Woll