andrew4582

Explicit operator example

Feb 10th, 2012
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.63 KB | None | 0 0
  1. using System;
  2.  
  3. class Apartment {
  4.     public string Name { get; set; }
  5.     public static explicit operator House(Apartment a) {
  6.         return new House() { Name = a.Name };
  7.     }
  8. }
  9.  
  10. class House {
  11.     public string Name { get; set; }
  12.     public static explicit operator Apartment(House h) {
  13.         return new Apartment() { Name = h.Name };
  14.     }
  15. }
  16.  
  17. class Program {
  18.     static void Main() {
  19.         House h = new House();
  20.         h.Name = "Broadway";
  21.  
  22.         // Cast a House to an Apartment.
  23.         Apartment a = (Apartment)h;
  24.  
  25.         // Apartment was converted from House.
  26.         Console.WriteLine(a.Name);
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment