Get the members of the current Type in C#

CsharpServer Side ProgrammingProgramming

To get the members of the current Type, the code is as follows −

Example

 Live Demo

using System;
using System.Reflection;
public class Demo {
   public static void Main() {
      Type type = typeof(Subject);
      try {
         FieldInfo fieldInfo = type.GetField("SubName");
         MemberInfo[] info = type.GetMembers();
         Console.Write("Members = ");
         for (int i = 0; i < info.Length; i++)
            Console.WriteLine(" {0}", info[i]);
         Console.WriteLine("FieldInfo = {0}", fieldInfo);
      }
      catch (ArgumentNullException e) {
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}
public class Subject {
   public string SubName = "Science";
}

Output

This will produce the following output −

Members =  System.String ToString()
 Boolean Equals(System.Object)
 Int32 GetHashCode()
 System.Type GetType()
 Void .ctor()
 System.String SubName
FieldInfo = System.String SubName

Example

Let us see another example −

 Live Demo

using System;
using System.Reflection;
public class Demo {
   public static void Main() {
      Type type = typeof(Subject);
      try {
         FieldInfo fieldInfo = type.GetField("SubName");
         MemberInfo[] info = type.GetMembers(BindingFlags.Public | BindingFlags.Instance);
         Console.Write("Members = ");
         for (int i = 0; i < info.Length; i++)
            Console.WriteLine(" {0}", info[i]);
         Console.WriteLine("FieldInfo = {0}", fieldInfo);
      }
      catch (ArgumentNullException e) {
         Console.Write("{0}", e.GetType(), e.Message);
      }
   }
}
public class Subject {
   public string SubName = "Science";
}

Output

This will produce the following output −

Members =  System.String ToString()
 Boolean Equals(System.Object)
 Int32 GetHashCode()
 System.Type GetType()
 Void .ctor()
 System.String SubName 
FieldInfo = System.String SubName
raja
Published on 11-Dec-2019 10:19:36
Advertisements