How do I provide custom cast support for my class?

You would need to override the conversion operator, using either implicit or explicit depending on whether you want users to have to cast it or whether you want it to happen automagically. Generally, one direction will always work, that’s where you use implicit, and the other direction can sometimes fail, that’s where you use explicit.

The syntax is like this:

public static implicit operator dbInt64(Byte x)
{  return new dbInt64(x); }

or

public static explicit operator Int64(dbInt64 x)
{
    if (!x.defined) throw new DataValueNullException();
    return x.iVal;
}

For your example, say from your custom Type (MyType –> byte[] will always work):

public static implicit operator byte[] (MyType x)
{
    byte[] ba = // put code here to convert x into a byte[]
    return ba;
}

or

public static explicit operator MyType(byte[] x)
{
    if (!CanConvert) throw new DataValueNullException();

    // Factory to convert byte[] x into MyType
    return MyType.Factory(x);
}

Leave a Comment