Search code examples
c#arraysiconvertible

C#: Get Bytearray from IConvertible


I'm currently working on a small project where I edit a binary file. Therefor I want to use the IConvertible Interface, since I can't create a Getter and Setter for every type.
Currently I'm working on the Setter which needs to convert the IConvertible object into a bytearray.

The Setter currently looks like this:
public void SetValue(UInt32 Offset, IConvertible Value) { }

Does anybody know a way in order to get a bytearray from the IConvertible Object, since BitConverter doesn't offer a native way of doing so.


Solution

  • IConvertible is not intended for this scenario, as reflected by the primary methods of IConvertible (ToString, ToUInt64, etc). There is an auxiliary ToType which could work, but most types do not support ToType with byte[] (for conversionType). If it did, then this would work:

    var blob = Convert.ChangeType(obj, typeof(byte[]));
    

    However, this is not something you should do, and it is not the intended usage. Frankly, your serialization details should usually exist separate to the objects.