Using reflection to show all fields/values of a struct.

  • Thread starter Thread starter Zytan
  • Start date Start date
Z

Zytan

This code works:

Type t = myVar.GetType();
System.Reflection.FieldInfo[] fields = t.GetFields();
foreach (System.Reflection.FieldInfo field in fields)
WriteLine(field.Name + " = " + field.GetValue(myVar);

But, when one of the fields is an array of string, this will just
print:

fieldName = System.String[]

How can I test to see if this type is an array of string, and handle
it differently? How can I use the return value of myField.GetType()
and test it against a string?

Zytan
 
To check the type of the field to see if it is an array of strings, you
can do:

field.FieldType = typeof(string[]);

Or, if you want something more dynamic, you can use the Type instance
exposed by FieldType and call the IsArray property to see if it is an array,
and then call GetElementType if it is an array.
 
To check the type of the field to see if it is an array of strings, you
can do:

field.FieldType = typeof(string[]);

Or, if you want something more dynamic, you can use the Type instance
exposed by FieldType and call the IsArray property to see if it is an array,
and then call GetElementType if it is an array.

Great, thanks, Nicholas

I forgot I also had this in my code already:

if (Object.ReferenceEquals(myVar.GetType(), typeof(Exception)))
{ ...... }

So, that should work, as well

Zytan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top