Defines and demonstrates implicit and explicit conversion operators for the MyString - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Defines and demonstrates implicit and explicit conversion operators for the MyString

Demo Code

using System;//w  w w .  j  ava2  s.  c o m
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
public class MyString
{
   public string Text
   {
      get;
      set;
   }
   public static explicit operator MyString(string str)
   {
      return new MyString() { Text = str };
   }
   public static implicit operator string(MyString w)
   {
      return w.Text;
   }
   public static explicit operator int(MyString w)
   {
      return w.Text.Length;
   }
   public override string ToString()
   {
      return Text;
   }
}
class MainClass
{
   static void Main(string[] args)
   {
      MyString word1 = new MyString() { Text = "Hello"};
      // implicitly convert the word to a string
      string str1 = word1;
      // explicitly convert the word to a string
      string str2 = (string)word1;
      Console.WriteLine("{0} - {1}", str1, str2);
      // convert a string to a word
      MyString word2 = (MyString)"Hello";
      // convert a word to an int
      int count = (int)word2;
      Console.WriteLine("Length of {0} = {1}", word2.ToString(), count);
      Console.WriteLine("\nMain method complete. Press Enter.");
      Console.ReadLine();
   }
}

Result


Related Tutorials