views:

165

answers:

2

Is there a way to ignore a field in the calculated of the struct size using Marshal.SizeOf

Ex:

public struct Message
{
   public ushort X;
   public ushort Y; // Ignore this field in the calculation
}

int size = Marshal.SizeOf(typeof(Message));

Right now size is 4. I want the size to be 2. Is there a way to do this?

A: 

I don't think that's possible. Why would you want to do that?

Zyphrax
+2  A: 

The only way I can think of doing it would be to create a Custom Marshaller and when you implement ICustomMarshaller.GetNativeDataSize, return 0. You would use MarshalAsAttribute to apply the custom marshaller to just that field. But, it won't marshal properly, so I don't know why you would want to do that.

JP Alioto