Search code examples
c#reflectionfieldinfo

How to convert fieldinfo to it's actual class object? using C#


i need to create program that navigate an object structure and print the structure of any “struct” provided as an argument.

These "structs" are defined as follows:

  • They have only public attributes
  • Each attribute can be of the following types:
    • “Structs”
    • Primitive (e.g. int), primitive wrapper (e.g. Integer) or String

the problem is when i'm trying to print data member which is a class or struct. i'm trying to to write a recursive function that gets an object and check each field in the object: if it's a class them i send again the curr field to the same function. else i print the value of the field.

this is my code. but when i send the fieldInfo to the function the code line: ---> Type objType = i_obj.GetType();

is getting me the next value: object.GetType returned {Name = "RtFieldInfo" FullName = System.Reflection.RtFieldInfo"} System.RuntimeType

    public static void getObj(object i_obj)
    {
        Type objType = i_obj.GetType();

        FieldInfo[] objField = objType.GetFields();

        foreach (FieldInfo member in objField)
        {
            Type memberType = member.FieldType;

            if(memberType.IsClass)
            {                    
                getObj(member);
            }

            else
            {
                Console.WriteLine(member.Name + " : " + member.GetValue(i_obj));
            }

        }
    }

how can i get the real object from fieldInfo ??


Solution

  • For the fields where IsClass is true you want to pass on the value of the field to the nested call to getObj. Also you might want to do some null checks:

    public static void getObj(object i_obj)
    {
        Type objType = i_obj.GetType();
    
        FieldInfo[] objField = objType.GetFields();
    
        foreach (FieldInfo member in objField)
        {
            Type memberType = member.FieldType;
    
            object memberValue = member.GetValue(i_obj); // <---
    
            if (memberValue == null)
            {
                Console.WriteLine(member.Name + " : null");
            }
            else if(memberType.IsClass)
            {                    
                getObj(memberValue); // <---
            }
            else
            {
                Console.WriteLine(member.Name + " : " + memberValue);
            }
    
        }
    }