Free mag vol1 | Page 476

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES DrawSquare((Square)rect); Console.ReadLine(); } Additional Explicit Conversions for the Square Type Now that you can explicitly convert Rectangles into Squares, let’s examine a few additional explicit conversions. Given that a square is symmetrical on all sides, it might be helpful to provide an explicit conversion routine that allows the caller to cast from an integer type into a Square (which, of course, will have a side length equal to the incoming integer). Likewise, what if you were to update Square such that the caller can cast from a Square into an int? Here is the calling logic: static void Main(string[] args) { ... // Converting an int to a Squa re. Square sq2 = (Square)90; Console.WriteLine("sq2 = {0}", sq2); } // Converting a Square to an int. int side = (int)sq2; Console.WriteLine("Side length of sq2 = {0}", side); Console.ReadLine(); and here is the update to the Square class: public struct Square { ... public static explicit operator Square(int sideLength) { Square newSq = new Square(); newSq.Length = sideLength; return newSq; } } public static explicit operator int (Square s) {return s.Length;} To be honest, converting from a Square into an integer may not be the most intuitive (or useful) operation. However, it does point out a very important fact regarding custom conversion routines: the compiler does not care what you convert to or from, as long as you have written syntactically correct code. Thus, as with overloading operators, just because you can create an explicit cast operation for a given type does not mean you should. Typically, this technique will be most helpful when you’re creating .NET structure types, given that they are unable to participate in classical inheritance (where casting comes for free). 416