1

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?

Community
  • 1
  • 1
Noah Roth
  • 9,060
  • 5
  • 19
  • 25
  • 5
    Try this: http://stackoverflow.com/a/3278956/113702 – Brook May 01 '12 at 15:45
  • 1
    The question is somewhat subjective, and you don't say *why* you store these values in a struct, or need to convert them to a byte array... but, in general, you are fighting against the language here. There are much easier ways to serialize an object's properties that are perfectly performant for most needs. So: what are you trying to accomplish? – Dan J May 01 '12 at 16:17

0 Answers0