Search code examples
c#casting

How do I provide custom cast support for my class?


How do I provide support for casting my class to other types? For example, if I have my own implementation of managing a byte[], and I want to let people cast my class to a byte[], which will just return the private member, how would I do this?

Is it common practice to let them also cast this to a string, or should I just override ToString() (or both)?


Solution

  • 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 - you can use implicit):

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

    or, if it might fail on occasion, use explicit...

    public static explicit operator MyType(byte[] x)
    {
        if (!CanConvert) throw new DataValueNullException();
    
        // Factory to convert byte[] x into MyType
        return MyType.Factory(x);
    }