CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
On a related note, consider value types (structures). Assume you have two .NET structures named
Square and Rectangle. Given that structures cannot leverage classic inheritance (as they are always
sealed), you have no natural way to cast between these seemingly related types.
While you could create helper methods in the structures (such as Rectangle.ToSquare()), C# lets you
build custom conversion routines that allow your types to respond to the () casting operator. Therefore,
if you configured the structures correctly, you would be able to use the following syntax to explicitly
convert between them as follows:
// Convert a Rectangle to a Square!
Rectangle rect;
rect.Width = 3;
rect.Height = 10;
Square sq = (Square)rect;
Creating Custom Conversion Routines
Begin by creating a new Console Application named CustomConversions. C# provides two keywords,
explicit and implicit, that you can use to control how your types respond during an attempted
conversion. Assume you have the following structure definitions:
public struct Rectangle
{
public int Width {get; set;}
public int Height {get; set;}
public Rectangle(int w, int h) : this()
{
Width = w; Height = h;
}
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 struct Square
{
public int Length {get; set;}
413