Kyle
Kyle

Reputation: 63

System.String does not implement the interface System.IConvertible

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

Upvotes: 4

Views: 2036

Answers (2)

Kirk Woll
Kirk Woll

Reputation: 77596

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.

Upvotes: 9

Jehof
Jehof

Reputation: 35544

System.String implement the interface IConvertible explicitly. See MSDN for reference.

So the methods are only "visible", when you assign a string to a variable of type IConvertible.

string mystring = "Hello World";

IConvertible convertible = mystring as IConvertible.

Upvotes: 5

Related Questions