implicit and explicit operator cast : Cast operator « Operator Overload « C# / CSharp Tutorial






using System;

    class MyType
    {
        int value;

        public MyType( int b )
        {
            value = b;
        }

        public static implicit operator int( MyType a )
        {
            return a.value;
        }

        public static explicit operator string( MyType a )
        {
            return "$" + a.value;
        }

        static void Main(string[] args)
        {
            MyType bal = new MyType( 777 );

            Console.WriteLine("since int conversion is implicit we can write");

            int i = bal;

            Console.WriteLine("string conveersion must be explicitly requested");

            string str = (string)bal;

            // this causes a compilation error
            // str = bal;

            System.Console.WriteLine( "i = {0} \nstr = {1}", i, str );
        }
    }
since int conversion is implicit we can write
string conveersion must be explicitly requested
i = 777
str = $777








8.11.Cast operator
8.11.1.implicit and explicit operator cast
8.11.2.explicit/implicit operator for Complex