Recursively describe an object structure C# with Example
Recursion is when a method calls itself. Preferably it will do so until a specific condition is met and then it will exit the method normally, returning to the point from which the method was called. If not, a stack overflow exception might occur due to too many recursive calls. /// /// Create an object structure the code can recursively describe /// public class Root { public string Name { get; set; } public ChildOne Child { get; set; } } public class ChildOne { public string ChildOneName { get; set; } public ChildTwo Child { get; set; } } public class ChildTwo { public string ChildTwoName { get; set; } } /// /// The console application with the recursive function DescribeTypeOfObject /// public class Program { static void Main(string[] args) { // point A, we call the function with type 'Root' DescribeTypeOfObject(typeof(Root)); Console.WriteLine("Press a key to exit"); Console.ReadKey(); } static void DescribeTypeOfObject(Type type) { // get all properties of this type Console.WriteLine($"Describing type {type.Name}"); PropertyInfo[] propertyInfos = type.GetProperties(); foreach (PropertyInfo pi in propertyInfos) { Console.WriteLine($"Has property {pi.Name} of type {pi.PropertyType.Name}"); // is a custom class type? describe it too if (pi.PropertyType.IsClass && !pi.PropertyType.FullName.StartsWith("System.")) { // point B, we call the function type this property DescribeTypeOfObject(pi.PropertyType); } } // done with all properties // we return to the point where we were called // point A for the first call // point B for all properties of type custom class } }