123
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UserConverts { class Program { static void Main(string[] args) { int a = 123; long b = a; // not explicit int c=(int)b;// explicit convert, I say to compiler "I know ehat am I doing" Base someBase; someBase = new Derived(); // not explicit Derived someDerived = (Derived)(someBase); // explicit Rectangle r = new Rectangle(15,4); Console.WriteLine(r.ToString()); r.Draw(); Console.WriteLine(); //converting Rectangle to square using explicit Square s = (Square)r; Console.WriteLine(r.ToString()); s.Draw(); Console.WriteLine(""); //converting Square to Rectangle using implicit Rectangle r2 = (Rectangle)s; Console.WriteLine(r2); r2.Draw(); Console.ReadLine(); } class Base { } class Derived : Base { } } public class Rectangle { public int Width { get; set; } public int Height { get; set; } public Rectangle(int w, int h) { Width = w; Height = h; } public Rectangle() { } public void Draw() { for (int i = 0; i < Height; i++) { for (int j = 0; j < Width; j++) { Console.Write("*"); } Console.WriteLine(); } } public override string ToString() { return string.Format("Width {0} Height {1} ",Width,Height); } public static implicit operator Rectangle(Square s) { Rectangle r = new Rectangle(); r.Height = s.Length; r.Width = 2 * s.Length; return r; } } public class Square { public int Length { get; set; } public Square(int l) { Length = l; } public Square() { } public void Draw() { for (int i = 0; i < Length; i++) { for (int j = 0; j < Length; j++) { Console.Write("*"); } Console.WriteLine(); } } // EXPLICIT RECTANGLE TO SQUARE public static explicit operator Square(Rectangle r) { Square s = new Square(); s.Length = r.Height; return s; } } } |