Felas
Felas

Reputation: 3

C# GetFields() extracting data from nested class

I want to get field's information from some object but get stucked on retrieving data from nested class. GetFields() from recursive call return FieldInfo[0].

Here code sample.

 public class Test1
    {
        public string Name;
        public int Id;
        public object Value;
        public Test2 Test;
    }

    public class Test2
    {
        public float Value;
        public bool IsEnable;
    }

    class Program
    {
        static void Main()
        {
            var test1 = new Test1
                {
                    Name = "Test 1",
                    Id = 1,
                    Value = false,
                    Test = new Test2
                        {
                            Value = 123,
                            IsEnable = true,
                        },
                };

            GetTypeFields(test1);

            Console.ReadLine();
        }

        public static void GetTypeFields(object data)
        {
            var fields = data.GetType().GetFields();

            foreach (var fi in fields)
            {
                var type = fi.FieldType;

                if (type.IsValueType || type == typeof(string) || type == typeof(object))
                {
                    Console.WriteLine(fi.FieldType + " : " + fi.Name + " = " + fi.GetValue(data));
                }

                if (type.IsClass && type != typeof (string) && type != typeof(object))
                {
                    GetTypeFields(fi);
                }
            }
        }
    }

Could someone help with this?

Upvotes: 0

Views: 1305

Answers (1)

Nevyn
Nevyn

Reputation: 2683

You are very close. In the second call, you need to call GetTypeFields(fi.GetValue(data)). Currently, you are providing the FieldInfo object to the second call, rather than the actual class object.

Upvotes: 2

Related Questions