Search code examples
c#reflectiondump

get all fields and datatypes of a c# class iteratively


I have huge C# classes defined with many fields/variables. Each variable could be a simple datatype or a list or another class ....

I want to dump all variables and their datatype iteratively going thru child classes as well. Is there any simple C# function/code to do this?

PS: I am not looking at run time object values. Just extract of name and datatype is enough.

RK


Solution

  • You could try to create the following setup. The GetData class will take as its single parameter the assembly, that you want to scan for different types. This class will then take all the classes and their child classes it can find, together with their fields and create a structured XML file which will hold that data.

    class GetData
    {
        public GetData(Assembly assembly)
        {
            var xml = new XDocument(new XElement("root"));
    
            foreach (var type in assembly.GetTypes())
            {
                var typeElement = new XElement("Class", new XElement("Name", type.Name));
    
                foreach (var field in type.GetFields())
                {
                    typeElement.Add(new XElement("Field",
                        new XElement("Name", field.Name),
                        new XElement("Type", field.FieldType)));
                }
    
                xml.Root.Add(typeElement);
            }
    
            Console.WriteLine(xml);
    
            xml.Save("Dump.xml");
        }
    }
    

    You can create this test class with an inner class so that you can be sure it will even work on this kind of setup.

    public class DbClass
    {
        public int ID;
        public string Name;
    
        public class DbChildClass
        {
            public int ChildID;
            public string Company;
        }
    }
    

    To get all the types from your currently executing assembly, simply execute the following lines of code.

    class Program
    {
        static void Main()
        {
            new GetData(Assembly.GetExecutingAssembly());
    
            Console.Read();
        }
    }