Mega Code Archive

 
Categories / C# Tutorial / Operator Overload
 

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 );         }     } since int conversion is implicit we can write string conveersion must be explicitly requested i = 777 str = $777