3

Playing around in Mono 2.10 REPL:

csharp> string a = "true";
csharp> a.ToBoolean(CultureInfo.InvariantCulture);
{interactive}(1,4): error CS1061: Type `string' does not contain a definition fo
r `ToBoolean' and no extension method `ToBoolean' of type `string' could be foun
d (are you missing a using directive or an assembly reference?)
C:\PROGRA~1\MONO-2~1.2\lib\mono\4.0\mscorlib.dll (Location of the symbol related
 to previous error)


csharp> ((IConvertible)a).ToBoolean(CultureInfo.InvariantCulture);
true
csharp>

According to docs, System.String implements IConvertible. If this is true, why does

a.ToBoolean(CultureInfo.InvariantCulture);

fail?

Why do I have to cast it to IConvertible to make ToBoolean work?

svick
  • 236,525
  • 50
  • 385
  • 514
Naonaem
  • 33
  • 2
  • In any case, you should not be using those conversion methods but instead, the parsing functions defined for the type or the `Convert` class. – Jeff Mercado Aug 26 '11 at 22:32

2 Answers2

7

As the documentation for ToBoolan() for string on MSDN states:

This member is an explicit interface member implementation. It can be used only when the String instance is cast to an IConvertible interface. The recommended alternative is to call the Convert.ToBoolean(String) method.

svick
  • 236,525
  • 50
  • 385
  • 514
2

The interface is explicitly implemented.

erikH
  • 2,286
  • 1
  • 17
  • 19
  • Interfaces that are implicitly implemented can be called directly. – erikH Aug 26 '11 at 22:29
  • 2
    Interfaces are not explicitly implemented, its members (like methods) are. For example, you can implement one member implicitly and another explicitly. – svick Aug 26 '11 at 22:30
  • @svick That's right. See also http://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation – erikH Aug 26 '11 at 22:35