0

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.
        }
    }
}
RLH
  • 15,230
  • 22
  • 98
  • 182
  • I wouldn't be too surprised if you would find that these fixed fields cannot be treated the usual way with reflection. Anyway, your best bet is to debug the application, and look at `f` and its properties in the debugger. – Kris Vandermotten Sep 12 '14 at 17:56
  • I have. I can get close to discerning something that looks to *possibly* be such a field, but I can't find all of the necessary pieces of information. I've not used reflection much before this requirement. Hopefully a 'guru' can help. – RLH Sep 12 '14 at 18:00

1 Answers1

2

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).

Michael
  • 3,099
  • 4
  • 31
  • 40