Initialization of a struct in C#?
<p>Some code I'm modifying makes extensive use of structs to communicate with some factory equipment by loading them to or from byte arrays.</p>

<p>Here's a made-up ultra-simplified example of such a struct.</p>

<pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct K_FOO
{
    public byte a_byte;    // 1 byte
    public BYTE3_TYPE b3;  // 3 bytes
    public int num;        // happens to be 4 bytes
}
</code></pre>

<p>BYTE3_TYPE looks like this...</p>

<pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class BYTE3_TYPE
{
    [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public byte[] L = new byte[3];
}
</code></pre>

<p>If I just do a </p>

<pre><code>    K_FOO origFoo = new K_FOO();
</code></pre>

<p>the int and the byte are initialized to 0's, I assume because they are native types, but the byte array b3 is *<em>un</em>*initialized - all nulls.   I have to explicitly load it, for example, </p>

<pre><code>    BYTE3_TYPE b3 = new BYTE3_TYPE();
    origFoo.b3 = b3;
</code></pre>

<p>... and I couldn't think of any alternative because structs don't take parameterless constructors but the real structs are huge.</p>

<p>But I noticed something interesting.  We have routines to copy these structs to and from byte arrays.     For example . . . </p>

<pre><code>   public static T ByteArrayToStructure&lt;T&gt;(byte[] buffer) where T : struct
    {
        int length = buffer.Length;
        IntPtr ptr = Marshal.AllocHGlobal(length);   // allocate (length) bytes
        Marshal.Copy(buffer, 0, ptr, length);  // copies into UNmanaged space
        T result = (T)Marshal.PtrToStructure(ptr, typeof(T));
        Marshal.FreeHGlobal(ptr);
        return result;
    }
</code></pre>

<p>...and if I call it... </p>

<pre><code>    K_FOO retFoo = ByteArrayToStructure&lt;K_FOO&gt;(buffer.bytes);
</code></pre>

<p>... the resulting struct is returned fully initialized, the bytes in the byte array have all had their space allocated so they could be loaded, apparently in the <em>PtrToStructure()</em> call.  This implies .Net "knows" how to initialize such a struct.   So is there some way to get .Net to do that for me so I can avoid writing hundreds of lines of explicit initialization code?    Thanks in advance!</p>
