Posts

Showing posts with the label Generic Constraints

Donate

Generic Method With BitConverter.GetBytes() Throws Error: CS1503 Argument 1: cannot convert from 'T' to 'bool'

Image
Hello And Good Day! There was a post in VBForums Generic Method with BitConverter.GetBytes problem on how to pass a T variable without causing the issue CS1503 Argument 1: cannot convert from 'T' to 'bool' private static byte [] GetBytes<T> (T valu) { var bytes = BitConverter.GetBytes(valu); if (BitConverter.IsLittleEndian) Array.Reverse(bytes); return bytes; } Since Generic Constraints for a numeric types isn't available at this time, I attempted to solve this issue by checking the type of T and then perform the conversion explicity. private static byte [] GetBytes<T>(T value ) { byte [] bytes; ushort val1; uint val2; Type t = typeof (T); if (t == typeof ( ushort )) { val1 = Convert.ToUInt16( value ); bytes = BitConverter.GetBytes(val1); } else if (t == t

Donate