User User - 3 months ago 13
C# Question

Cannot implicitly convert type 'X' to 'string' - when and how it decides that it "cannot"?

Right now I'm having it with

Guid
s.

I certainly remember that throughout the code in some places this implicit conversion works, in others it does not. Until now I fail to see the pattern.

How the compiler decides when it cannot? I mean, the type method
Guid.ToString()
is present, isn't it called whenever this transformation is needed?

Can someone please tell me under what circumstances this transformation is done automatically and when I have to call
myInstance.ToString()
explicitly?

Answer

In short, when there is an implicit or explicit conversion operator defined:

class WithImplicit {
    public static implicit operator string(WithImplicit x) {
        return x.ToString();}
}
class WithExplicit {
    public static explicit operator string(WithExplicit x) {
        return x.ToString(); }
}
class WithNone { }

class Program {
    static void Main() {
        var imp = new WithImplicit();
        var exp = new WithExplicit();
        var none = new WithNone();
        string s1 = imp;
        string s2 = (string)exp;
        string s3 = none.ToString();
    } 
}