I’d like to use a GetBytes extension method on the List class…
public static class Extensions
{
public static byte[] GetBytes<T>(this ICollection<T> col)
{
List<byte> bytes = new List<byte>();
foreach (T t in col)
bytes.AddRange(BitConverter.GetBytes(t));
return bytes.ToArray();
}
}
When I compile, I am receiving a compiler error stating that Argument ‘1’: cannot convert from ‘T’ to ‘double’. Can anyone explain to me what the issue is?
BitConverter doesn’t have a GetBytes implementation that works on arbitrary types. You must pass an argument of the correct type, such as double, int, etc.
The compiler is not finding an appropriate overload, and “defaulting” to the double overload, then reporting it as a compiler error.
In order to use this on a general type, you’ll need to also pass in a Func that converts to bytes. This would work:
You could then use this like:
Unfortunately, the “BitConverter.GetBytes” line (or some other function to do this conversion) makes the API call a little less “pretty”, but it does work correctly. This could be removed for specific types of T by adding overloads, such as:
Edit: Since you need to avoid SelectMany, you can just write the main function the same way you did previously. SelectMany just makes this simpler: