Nefzen Nefzen - 1 year ago 96
C# Question

how to convert a value type to byte[] in C#?

I want to do the equivalent of this:

byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;

yes, it's a byte now, but consider I want to change it in the future? how do I make byteArray contain content? (I don't care to copy it).

Answer Source

The BitConverter class might be what you are looking for. Example:

int input = 123;
byte[] output = BitConverter.GetBytes(input);

If your enum was known to be an Int32 derived type, you could simply cast its values first:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download