implicit and explicit operator cast : Cast operator : Operator Overload C# Examples


C# Examples » Operator Overload » Cast operator »

 

implicit and explicit operator cast









    
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  );
                }
        }
    
   
  
   



Output

since int conversion is implicit we can write
string conveersion must be explicitly requested
i = 777
str = $777


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Operator Overload
» Cast operator