Generic BitConverter.GetBytes for primitive data types?

I had a similar problem and solved it by converting the generic T type into an object first and then call the BitConverter.GetMethod(), i.e.

I had a similar problem and solved it by converting the generic T type into an object first and then call the BitConverter.GetMethod(), i.e. Dim obj As Object = CType(Value, T) Dim bytes As Byte() = BitConverter. GetBytes(obj).

Solved it myself. Using a stripped-down version of the solution provided in my question, "Faster way to convert from a String to generic type T when T is a valuetype? ", I was able to to create an extension method to a generic type called GenericGetBytes that would use the same delegate tricks to access the appropriate GetBytes method in the System.

BitConverter class. This would preserve a decent amount of performance without me having to write up a bunch of overloaded functions for each type. Code: Friend Function GenericGetBytes(Of T As Structure)(ByVal value As T) As Byte() Return GenericBitConverter(Of T).

GetBytes(value) End Function Private Class GenericBitConverter(Of T As Structure) Private Sub New() End Sub Friend Delegate Function GetBytesFunc(ByVal value As T) As Byte() Friend Shared ReadOnly GetBytes As GetBytesFunc = FetchGetBytesFunc() Private Shared Function FetchGetBytesFunc() As GetBytesFunc Return DirectCast(GetBytesFunc. CreateDelegate(GetType(GetBytesFunc), GetType(BitConverter). GetMethod("GetBytes", New Type() {GetType(T)})), GetBytesFunc) End Function End Class Invocation: Public Sub Foobar(Of T As Structure)(ByVal value As T) Debug.

Print(BitConverter. ToString(value. GenericGetBytes)) End Sub Call Foobar(Of Int16)(42) Output: 2A-00 Edit: And then I discover that the CType operator cannot convert from a base class to a derived class, which means the entire goal of this question and answer just became moot, as I have to move all my CType operators back to the derived classes.Hah.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions