1. Home
  2. Docs
  3. C# Programming
  4. Operators
  5. Implicit Cast and Explicit Cast Operators

Implicit Cast and Explicit Cast Operators

C# allows user-defined types to control assignment and casting through the use of the explicit and implicit keywords. The signature of the method takes the form:

public static <implicit/explicit> operator <ResultingType>(<SourceType> myType)

The method cannot take any more arguments, nor can it be an instance method. It can, however, access any private members of type it is defined within. An example of both an implicit and explicit cast:

public class BinaryImage
{
  private bool[] _pixels;

  public static implicit operator ColorImage(BinaryImage im)
  {
    return new ColorImage(im);
  }

  public static explicit operator bool[](BinaryImage im)
  {
    return im._pixels;
  }
}

Allowing the following cast syntax:

var binaryImage = new BinaryImage();
ColorImage colorImage = binaryImage; // implicit cast, note the lack of type
bool[] pixels = (bool[])binaryImage; // explicit cast, defining the type

The cast operators can work both ways, going from your type and going to your type:

public class BinaryImage
{
  public static explicit operator ColorImage(BinaryImage im)
  {
    return new ColorImage(im);
  }

  public static explicit operator BinaryImage(ColorImage cm)
  {
    return new BinaryImage(cm);
  }
}

Finally, the as keyword, which can be involved in casting within a type hierarchy, is not valid in this situation. Even after defining either an explicit or implicit cast, you cannot do:

ColorImage cm = myBinaryImage as ColorImage;

It will generate a compilation error

Was this article helpful to you? Yes No

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *