CHAPTER 23

image

Custom Conversions

This chapter covers how to define custom type conversions for an object. As can be seen in the example below, there is a class called MyNum with a single int field and a constructor. With a custom type conversion, it is possible to allow an int to be implicitly converted to an object of this class.

class MyNum
{
  public int val;
  public MyNum(int i) { val = i; }
}

Implicit conversion methods

For this to work an implicit conversion method needs to be added to the class. This method’s signature looks similar to that used for unary operator overloading. It must be declared as public static and includes the operator keyword. However, instead of an operator symbol the return type is specified, which is the target type for the conversion. The single parameter will hold the value that is to be converted. The implicit keyword is also included, which specifies that the method is used to perform implicit conversions.

public static implicit operator MyNum(int a)
{
  return new MyNum(a);
}

With this method in place an int can be implicitly converted to a MyNum object.

MyNum a = 5;

Another conversion method can be added that handles conversions in the opposite direction, from a MyNum object to an int.

public static implicit operator int(MyNum a)
{
  return a.val;
}

Explicit conversion methods

To prevent potentially unintended object type conversions by the compiler, the conversion method can be declared as explicit instead of implicit.

public static explicit operator int(MyNum a)
{
  return a.val;
}

The explicit keyword means that the programmer has to specify an explicit cast in order to invoke the type conversion method. In particular, explicit conversion methods should be used if the result of the conversion leads to loss of information, or if the conversion method may throw exceptions.

MyNum a = 5;
int i = (int)a;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.124.83