C# – Get Data from the Byte Array

cdesignnetobject-oriented

I have a byte array and a value defining the type of the data stored in it (string, int, …). What is the best way to get this data? I have two options in my mind:

  1. Call a method which gives the type of the data and based on that call a method which gives me the correct data.
  2. Call a method which returns both – the data (as object) and also the type of the data (DateTime, float[], …).

I am not sure if there is something better, nor which one of these methods is better. If
Type GiveMeDataType(); and e.g. string GiveMeString();
or
MyClass GiveMeData(); with MyClass { public Type DataType; public object Data; }

I would like to take the best approach for the best readability and maintainability (add support for additional data types and so on), so I don't think that too many switch statements in different parts of code is the best thing to do.

Best Answer

I think a general pattern for this is as follows

public interface IData
{
    Type Type {get;set;}
    byte[] Data {get;set;}
}

and then many:

public interface IDataConverter<T>
{
    T Convert(byte[] data);
    bool CanConvert(Type type);
}

So you can make a IDataConverter for whatever types you want, and the Converter has a list of these which it loops through, calling CanConvert. If that returns true, it calls the Convert Function and returns the result

class Converter
{
    private List<object> converters;
    public void AddConverter<T>(IDataConverter<T> converter)
    {
        this.converters.Add(converter);
    }
    public T Convert<T>(IData data) where T:class
    {
        var ret = converters
                .Select(i => ((dynamic)i))
                .Where(i => i.CanConvert(data.Type))
                .FirstOrDefault()?
                .Convert(data.Data)
                ;

        return ret as T;
    }
}

Edit: as you can see shoehorning in the generic type in there is tricky. You are probably better using the same pattern but just returning object

Related Topic