Home > Software engineering >  How to get the StructLayoutAttribute.Pack field applied to a struct in c#
How to get the StructLayoutAttribute.Pack field applied to a struct in c#

Time:11-14

Im bulding a generic type, limited to some kind of structs, and need to validate that have [StructLayout(LayoutKind.Sequential, Pack = 1)] attribute applied.

I validate struct kind in base constructor:

public abstract class IotDeviceData<T> where T : struct
{
  protected T _data;

  protected IotDeviceData()
  {
    IotDeviceData<T>.IsAnAllowedStruct();
    _data = new T();
  }
}

I can check that LayoutKind.Sequential is applied.

private static void IsAnAllowedStruct()
{
  var t = typeof(T);
  if(!t.IsLayoutSequential)
  {
    throw (new ArgumentException($"Struct type {t} must have a sequential layout."));
  }
}

But, how to check that Pack is 1 ?

CodePudding user response:

You can get the StructLayoutAttribute and inspect its Pack directly:

if ((type.StructLayoutAttribute?.Pack ?? 0) != 1) {
    throw (new ArgumentException($"Struct type {type} must have a pack of 1"));
}
  • Related