I am trying to find a way to with reflected field information for fields on structs. My structs often contain fixed-width byte arrays. When I encounter one of these arrays while iterating over the list of struct fields, I need to catch if a field is an array and handle the array differently than my other field types. How can I do this?
As an example, here is a sample struct and the following method also articulates my problem?
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public unsafe struct MyStruct
{
public int IntegerVal;
public unsafe fixed byte MyByteBuff[20];
}
//Later in code...
public static void WorkWithStructs(Type t) //t will always be a struct
{
foreach (var f in t.GetFields())
{
if (f.FieldType == typeof(int)
{
//Do Int work
}
else if (???) //Test for a fixed-width byte array
{
// If MyStruct were passed to this method, this is where I
// would need to handle the MyByteBuff field. Specifically,
// I need to discern the object type (in this case a byte)
// as well as the length in bytes.
}
}
}
You can check for the presence of the FixedBufferAttribute
custom attribute on your field types (found in the CustomAttributes
collection of the type.
In your case, you be able to check for the presence of an attribute that matches the following:
[FixedBufferAttribute(typeof(Byte), 20)]
(adding the FixedBufferAttribute
is done automatically - if you try to add it manually, you will get an error saying to use the fixed
keyword instead).