Skip to content

Conversion Methods

Mario Gutierrez edited this page Jan 7, 2017 · 1 revision

Explicit.

public static explicit operator Square(Rectangle r)
{
  return new Square(r.Height);
}

You can now explicitly cast from Rectangle to Square.

Rectangle myRectangle = new Rectangle(4, 4);
Square mySquare = (Square)myRectangle;

Implicit.

public static implicit operator Rectangle(Square s)
{
  return new Rectangle(s.Length, s.Length);
}

You can not implicitly cast from Square to Rectangle.

Square mySquare =  new Square(4);
Rectangle myRectangle = mySquare;

In the implicit case, you also get the explicit cast for free. This makes sense because if it happens automatically, you should also be allowed to be verbose about it.

Rectangle myRectangle2 = (Rectangle)mySquare;

Conversion methods can be defined in structs as well.

Clone this wiki locally