Runtime conversion of a generic Object to its underlying type

Ever have to do manual serialization of data in a DataSet?  The challenge is being able to call BitConverter.GetBytes on the data element when at compile time you have no idea what it’s type is, and GetBytes doesn’t accept an Object (though I’d argue maybe it should and attempt to convert the underlying type if it’s resolvable).


Here’s my solution:



byte[] elementBytes = (byte[])typeof(BitConverter).GetMethod(
   
“GetBytes”, new Type[] { dataRow[columnNumber].GetType() }).Invoke(
    null, new object[] { dataRow[columnNumber] });

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s