I have a data array of bytes, however this array can hold any unsigned number (byte/ushort/uint/ulong) as bytes.
The problem with this is retrieving the data again into the required type: I want the responsibility of converting the data back to the required datatype in the handler class, and not the one requesting the data again (which could convert a returned byte array representing the value).
Furthermore, ref or out variables, though is one solution, are a hassle as members I'm assigning are not necessarily of the type I'm returning (read explicit enums):
public enum SomeEnum : ulong
{
// ...
}
The functions I have at the moment are:
/// <summary>
/// Get data (byte)
/// </summary>
public byte GetDataByte(byte dataIndex)
{
return this.Data[dataIndex];
}
/// <summary>
/// Get data (ushort)
/// </summary>
public ushort GetDataUshort(byte startingDataIndex)
{
ushort output = 0;
for (byte i = startingDataIndex; i < this.Data.Length && i < sizeof(ushort); i++)
{
output |= (ushort)(this.Data[i] << (i * 8));
}
return output;
}
/// <summary>
/// Get data (uint)
/// </summary>
public uint GetDataUint(byte startingDataIndex)
{
uint output = 0;
for (byte i = startingDataIndex; i < this.Data.Length && i < sizeof(uint); i++)
{
output |= ((uint)this.Data[i] << (i * 8));
}
return output;
}
/// <summary>
/// Get data (ulong)
/// </summary>
public ulong GetDataUlong(byte startingDataIndex)
{
ulong output = 0;
for (byte i = startingDataIndex; i < this.Data.Length && i < sizeof(ulong); i++)
{
output |= ((ulong)this.Data[i] << (i * 8));
}
return output;
}
Could this be combined into one function, and how would I go about doing that? Like
SomeEnum member = (SomeEnum)GetData<ulong>(dataIndex);
but
GetData<byte>(0);
public T GetData<T>(byte startingDataIndex) // T would be byte during runtime
{
return this.Data[dataIndex]; // Compiler: Er, T? Byte? what?
}
or
/// <summary>
/// Get data (T)
/// </summary>
public T GetData<T>(byte startingDataIndex)
{
T output = 0; // Compiler: derp, this isn't an integer.
for (byte i = startingDataIndex; i < this.Data.Length && i < System.Runtime.InteropServices.Marshal.SizeOf(typeof(T)); i++)
{
output |= (T)(this.Data[i] << (i * 8)); // Compiler: nor is this!
}
return output;
}
Or am I really better off leaving as separate functions and maintaining them all?