Get the types nested within the current Type C#

CsharpServer Side ProgrammingProgramming

To get the types nested within the current Type, the code is as follows −

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      Type type1 = typeof(Subject);
      try {
         Type[] type2 = type1.GetNestedTypes();
         Console.WriteLine("Nested Types...");
         for (int i = 0; i < type2.Length; i++)
            Console.WriteLine("{0} ", type2[i]);
      }
      catch (ArgumentNullException e) {
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}
public class Subject {
   public class BasicSubject {
      //
   }
   public class AdvSubject {
      //
   }
}

Output

This will produce the following output −

Nested Types...
Subject+BasicSubject
Subject+AdvSubject

Example

Let us see another example −

 Live Demo

using System;
using System.Reflection;
public class Demo {
   public static void Main() {
      Type type1 = typeof(Subject);
      try {
         Type[] type2 = type1.GetNestedTypes(BindingFlags.Public);
         Console.WriteLine("Nested Types...");
         for (int i = 0; i < type2.Length; i++)
            Console.WriteLine("{0} ", type2[i]);
      }
      catch (ArgumentNullException e) {
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}
public class Subject {
   public class BasicSubject {
      //
   }
   public class AdvSubject {
      //
   }
}

Output

This will produce the following output −

Nested Types...
Subject+BasicSubject
Subject+AdvSubject
raja
Published on 11-Dec-2019 10:52:59
Advertisements