Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

reflection

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

like image 806
Tony Avatar asked Jul 07 '10 11:07

Tony


2 Answers

As an example:

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    public static class MyDictionary
    {
        public static int[] intArray = new int[] { 0, 1, 2 };
        public static string[] stringArray = new string[] { "zero", "one", "two" };
    }

    static class Program
    {
        static void Main(string[] args)
        {
            FieldInfo[] fields = typeof(MyDictionary).GetFields();

            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsArray)
                {
                    Array array = field.GetValue(null) as Array;

                    Console.WriteLine("Type: " + array.GetType().GetElementType().ToString());
                    Console.WriteLine("Length: " + array.Length.ToString());
                    Console.WriteLine("Values");
                    Console.WriteLine("------");

                    foreach (var element in array)
                        Console.WriteLine(element.ToString());
                }

                Console.WriteLine();
            }

            Console.Readline();
        }
    }
}
like image 71
George Howarth Avatar answered Sep 24 '22 19:09

George Howarth


Edit after your edit: Note that what you have is reflection objects, not objects or values related to your own class. In other words, those FieldInfo objects you have there are common to all instances of your class. The only way to get to the string arrays is to use those FieldInfo objects to get to the field value of a particular instance of your class.

For that, you use FieldInfo.GetValue. It returns the value of the field as an object.

Since you already know they are string arrays, that simplifies things:

If the fields are static, pass null for the obj parameter below.

foreach (var fi in fields)
{
    string[] arr = (string[])fi.GetValue(obj);
    ... process array as normal here
}

If you want to ensure you only process fields with string arrays:

foreach (var fi in fields)
{
    if (fi.FieldType == typeof(string[]))
    {
        string[] arr = (string[])fi.GetValue(obj);
        ... process array as normal here
    }
}
like image 39
Lasse V. Karlsen Avatar answered Sep 25 '22 19:09

Lasse V. Karlsen