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;