CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
public Square(int l) : this()
{
Length = l;
}
public void Draw()
{
for (int i = 0; i < Length; i++)
{
for (int j = 0; j < Length; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
public override string ToString()
{ return string.Format("[Length = {0}]", Length); }
}
// Rectangles can be explicitly converted
// into Squares.
public static explicit operator Square(Rectangle r)
{
Square s = new Square();
s.Length = r.Height;
return s;
}
Note You’ll notice in the Square and Rectangle constructors, I am explicitly chaining to the default constructor.
The reason is that if you have a structure, which makes use of automatic property syntax (as we do here), the
default constructor must be explicitly called (from all custom constructors) to initialize the private backing fields.
Yes, this is a very quirky rule of C#, but after all, this is an advanced topics chapter.
Notice that this iteration of the Square type defines an explicit conversion operator. Like the process
of overloading an operator, conversion routines make use of the C# operator keyword, in conjunction
with the explicit or implicit keyword, and must be defined as static. The incoming parameter is the
entity you are converting from, while the operator type is the entity you are converting to.
In this case, the assumption is that a square (being a geometric pattern in which all sides are of
equal length) can be obtained from the height of a rectangle. Thus, you are free to convert a Rectangle
into a Square, as follows:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Conversions *****\n");
414