views:

397

answers:

1

Why I cannot define both implicit and explicit operators like so?

    public class C
    {
        public static implicit operator string(C c)
        {
            return "implicit";
        }

        public static explicit operator string(C c)
        {
            return "explicit";
        }
    }

You can do this hack though :)

    class Program
    {
        public class A
        {

        }

        public class B
        {
            public static implicit operator A(B b)
            {
                Console.WriteLine("implicit");
                return new A();
            }
        }

        public class C : B
        {
            public static explicit operator A(C c)
            {
                Console.WriteLine("explicit");
                return new A();
            }
        }

        static void Main(string[] args)
        {
            C c = new C();

            A a = c;
            A b = (A) c;
        }
    }

This prints:

implicit
explicit
+2  A: 

I don't know the technical limitation that prevents this, but I think they would have done this to prevent people from shooting their own feet off.

string imp = new C(); // = "implicit"
string exp = (string)new C(); // = "explicit"

That would drive me bonkers and makes no sense, C should only cast to a string 1 way, not 2 different ways.

Samuel
You can do it two way, you just cannot do a custom conversion for both.
Prankster
No you cannot do it, ToString is not a cast operator.
Samuel
"Example" updated
Prankster