esac
esac

Reputation: 24695

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)?

Upvotes: 122

Views: 72766

Answers (4)

Charles Bretana
Charles Bretana

Reputation: 146597

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);
}

Upvotes: 133

Konstantin Spirin
Konstantin Spirin

Reputation: 21321

For custom cast support you need to provide cast operators (explicit or implicit). The following example of EncodedString class is a simplistic implementation of string with custom encoding (may be useful if you have to process huge-huge strings and run into memory consumption problems because .Net strings are Unicode - every character takes 2 bytes of memory - and EncodedString can take 1 byte per char).

EncodedString can be converted to byte[] and to System.String. Comments in code shed some light and also explain an example when implicit conversion can be dangerous.

Usually you need a very good reason to declare any conversion operators in the first place because.

Further reading is available on MSDN.

class Program
{
    class EncodedString
    {
        readonly byte[] _data;
        public readonly Encoding Encoding;

        public EncodedString(byte[] data, Encoding encoding)
        {
            _data = data;
            Encoding = encoding;
        }

        public static EncodedString FromString(string str, Encoding encoding)
        {
            return new EncodedString(encoding.GetBytes(str), encoding);
        }

        // Will make assumption about encoding - should be marked as explicit (in fact, I wouldn't recommend having this conversion at all!)
        public static explicit operator EncodedString(byte[] data)
        {
            return new EncodedString(data, Encoding.Default);
        }

        // Enough information for conversion - can make it implicit
        public static implicit operator byte[](EncodedString obj)
        {
            return obj._data;
        }

        // Strings in .Net are unicode so we make no assumptions here - implicit
        public static implicit operator EncodedString(string text)
        {
            var encoding = Encoding.Unicode;
            return new EncodedString(encoding.GetBytes(text), encoding);
        }

        // We have all the information for conversion here - implicit is OK
        public static implicit operator string(EncodedString obj)
        {
            return obj.Encoding.GetString(obj._data);
        }
    }

    static void Print(EncodedString format, params object[] args)
    {
        // Implicit conversion EncodedString --> string
        Console.WriteLine(format, args);
    }

    static void Main(string[] args)
    {
        // Text containing russian letters - needs care with Encoding!
        var text = "Привет, {0}!";

        // Implicit conversion string --> EncodedString
        Print(text, "world");

        // Create EncodedString from System.String but use UTF8 which takes 1 byte per char for simple English text
        var encodedStr = EncodedString.FromString(text, Encoding.UTF8);
        var fileName = Path.GetTempFileName();

        // Implicit conversion EncodedString --> byte[]
        File.WriteAllBytes(fileName, encodedStr);

        // Explicit conversion byte[] --> EncodedString
        // Prints *wrong* text because default encoding in conversion does not match actual encoding of the string
        // That's the reason I don't recommend to have this conversion!
        Print((EncodedString)File.ReadAllBytes(fileName), "StackOverflow.com");

        // Not a conversion at all. EncodingString is instantiated explicitly
        // Prints *correct* text because encoding is specified explicitly
        Print(new EncodedString(File.ReadAllBytes(fileName), Encoding.UTF8), "StackOverflow.com");

        Console.WriteLine("Press ENTER to finish");
        Console.ReadLine();
    }
}

Upvotes: 3

LukeH
LukeH

Reputation: 269628

You can declare conversion operators on your class using either the explicit or implicit keywords.

As a general rule-of-thumb, you should only provide implicit conversion operators when the conversion can't possibly fail. Use explicit conversion operators when the conversion might fail.

public class MyClass
{
    private byte[] _bytes;

    // change explicit to implicit depending on what you need
    public static explicit operator MyClass(byte[] b)
    {
        MyClass m = new MyClass();
        m._bytes = b;
        return m;
    }

    // change explicit to implicit depending on what you need
    public static explicit operator byte[](MyClass m)
    {
        return m._bytes;
    }
}

Using explicit means that users of your class will need to do an explicit conversion:

byte[] foo = new byte[] { 1, 2, 3, 4, 5 };
// explicitly convert foo into an instance of MyClass...
MyClass bar = (MyClass)foo;
// explicitly convert bar into a new byte[] array...
byte[] baz = (byte[])bar;

Using implicit means that users of your class don't need to perform an explicit conversion, it all happens transparently:

byte[] foo = new byte[] { 1, 2, 3, 4, 5 };
// imlpicitly convert foo into an instance of MyClass...
MyClass bar = foo;
// implicitly convert bar into a new byte[] array...
byte[] baz = bar;

Upvotes: 39

Chris Chilvers
Chris Chilvers

Reputation: 6479

I prefer to have some method that will do that rather than overloading the cast operator.

See explicit and implicit c# but note that from that example, using the explicit method, if you do:

string name = "Test";
Role role = (Role) name;

Then everything is fine; however, if you use:

object name = "Test";
Role role = (Role) name;

You will now get an InvalidCastException because string cannot be cast to Role, why, the compiler only looks for implicit/explicit casts at compile time based upon their compiled type. In this case the compiler sees name as an object rather than string, and thus doesn't use Role's overloaded operator.

Upvotes: 7

Related Questions