Class/struct and Marshal.SizeOf

From: SB (stormfire1_at_yahoo.com)
Date: 02/20/05


Date: Sun, 20 Feb 2005 07:04:00 -0500

I feel dumb to ask because I bet this is a simple question...

Looking at the code below, can someone please explain why I get two
different values in my Marshal.SizeOf calls (see the commented lines)?

TIA!
sb

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct MyStruct
{
    public short a;
    public short b;
    public short c;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MyClass
{
    public short a;
    public short b;
    public short c;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MyStructTestClass
{
    [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,
SizeConst = 256)]
    public MyStruct[] dummy;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MyClassTestClass
{
    [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,
SizeConst = 256)]
    public MyClass[] dummy;
}

// test code...
private void testButton_Click(object sender, EventArgs e)
{
    MyStruct myStructTest = new MyStruct();
    MessageBox.Show("myStructTest size: " +
Marshal.SizeOf(myStructTest).ToString());//will show size of 6

    MyClass myClassTest = new MyClass();
    MessageBox.Show("myClassTest size: " +
Marshal.SizeOf(myClassTest).ToString());//will show size of 6

    MyStructTestClass myStructClass = new MyStructTestClass();
    MessageBox.Show("myStructClass size: " +
Marshal.SizeOf(myStructClass).ToString());//will show size of 1536

    MyClassTestClass myClassClass = new MyClassTestClass();
    MessageBox.Show("myClass2 size: " +
Marshal.SizeOf(myClassClass).ToString());//will show size of 1024???!!
}