Free mag vol1 | Page 475

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES // Make a Rectangle. Rectangle r = new Rectangle(15, 4); Console.WriteLine(r.ToString()); r.Draw(); Console.WriteLine(); } // Convert r into a Square, // based on the height of the Rectangle. Square s = (Square)r; Console.WriteLine(s.ToString()); s.Draw(); Console.ReadLine(); The output can be seen here: ***** Fun with Conversions ***** [Width = 15; Height = 4] *************** *************** *************** *************** [Length = 4] **** **** **** **** While it may not be all that helpful to convert a Rectangle into a Square within the same scope, assume you have a function that has been designed to take Square parameters. // This method requires a Square type. static void DrawSquare(Square sq) { Console.WriteLine(sq.ToString()); sq.Draw(); } Using your explicit conversion operation on the Square type, you can now pass in Rectangle types for processing using an explicit cast, like so: static void Main(string[] args) { ... // Convert Rectangle to Square to invoke method. Rectangle rect = new Rectangle(10, 5); 415