User User - 2 years ago 118
C# Question

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

Right now I'm having it with


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
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

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download