I would like to have a helper method for converting byte array to generic type value:
public static T BytesToValue<T>(byte[] bytes)
{
int pos = 0;
T result = default;
foreach (byte b in bytes)
{
//Cannot convert from type byte to T error here
result |= ((T)b) << pos;
pos += 8;
}
return result;
}
The problem is that the compiler gives the error.
The method will primarily be used for getting int and long values and performance is very critical.
How can this be fixed?
Bitwise operators can't be used on generic type parameters.
Even this simple cast does not compile:
result = (T)b;
But we can write this that compiles (usefull for other case):
result = (T)Convert.ChangeType(b, typeof(T));
So this does not compile:
result |= ( (T)Convert.ChangeType(b, typeof(T)) ) << pos;