Possible Duplicate:
How to Convert Structure to byte array in C#?
So I'm coming from C++, and converting a struct/class to an array and vice-versa was simple and straightforward. I love C# and the .Net framework, but things like this I've noticed to be quite difficult and obnoxious to accomplish.
So I have a struct with floats. I need to transfer them to a byte array. Currently I have the struct 'wrapped' within a class and just expose the members through properties. But I find that copying this struct to an array is difficult. I know 'unsafe' code and pointers in C# is generally a big no-no and should be avoided, but would doing this be considered a bad programming practice?
public class LevelOfDetail {
private LODDataStruct data;
public float Scale {
get {
return data.Scale;
}
set {
data.Scale = value;
}
}
public float Brightness {
get {
return data.Brightness;
}
set {
data.Brightness = value;
}
}
public float Sway {
get {
return data.Sway;
}
set {
data.Sway = value;
}
}
public float Detail {
get {
return data.Detail;
}
set {
data.Detail = value;
}
}
public float Distance {
get {
return data.Distance;
}
set {
data.Distance = value;
}
}
public unsafe void CopyTo(void* dest) {
*((LODDataStruct*)dest) = data;
}
public unsafe void CopyFrom(void* src) {
data = *((LODDataStruct*)src);
}
private struct LODDataStruct {
public float Scale;
public float Brightness;
public float Sway;
public float Detail;
public float Distance;
};
};
Is this bad way to do this? I like it because it takes a single line of code to copy and it might be a tiny bit faster than getting the individual bytes from each float and copying each one by one.
Is there a better way to do this?