Alex Rivera | Logout

C# Reflection : how to get an array values & length?

Asked 2010-07-07T11:35:53.607
18
FieldInfo[] fields = typeof(MyDictionary).GetFields();

MyDictionary is a static class, all fields are string arrays.

How to get get the Length value of each array and then itearate through all elements ? I tried the cast like:

field as Array

but it causes an error

Cannot convert type 'System.Reflection.FieldInfo' to 'System.Array' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

Edit
Report

1 Answer

4

Like this:

FieldInfo[] fields = typeof(MyDictionary).GetFields();
foreach (FieldInfo info in fields) {
  string[] item = (string[])info.GetValue(null);
  Console.WriteLine("Array contains {0} items:", item.Length);
  foreach (string s in item) {
    Console.WriteLine("  " + s);
  }
}
answered 2010-07-07T11:50:23.887

Your Answer