Stats

Contributors: 2 Tuesday, July 26, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Implicit Cast and Explicit Cast Operators

Download c# eBook

Example

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.