CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
Defining Implicit Conversion Routines
So far, you have created various custom explicit conversion operations. However, what about the
following implicit conversion?
static void Main(string[] args)
{
...
Square s3 = new Square();
s3.Length = 83;
// Attempt to make an implicit cast?
Rectangle rect2 = s3;
}
Console.ReadLine();
This code will not compile, given that you have not provided an implicit conversion routine for the
Rectangle type. Now here is the catch: it is illegal to define explicit and implicit conversion functions on
the same type if they do not differ by their return type or parameter set. This might seem like a
limitation; however, the second catch is that when a type defines an implicit conversion routine, it is
legal for the caller to make use of the explicit cast syntax!
Confused? To clear things up, let’s add an implicit conversion routine to the Rectangle structure
using the C# implicit keyword (note that the following code assumes the width of the resulting
Rectangle is computed by multiplying the side of the Square by 2):
public struct Rectangle
{
...
public static implicit operator Rectangle(Square s)
{
Rectangle r = new Rectangle();
r.Height = s.Length;
}
}
// Assume the length of the new Rectangle with
// (Length x 2).
r.Width = s.Length * 2;
return r;
With this update, you are now able to convert between types, as follows:
static void Main(string[] args)
{
...
// Implicit cast OK!
Square s3 = new Square();
s3.Length= 7;
Rectangle rect2 = s3;
Console.WriteLine("rect2 = {0}", rect2);
417