Type.GetMember() Method in C#


The Type.GetMember() method in C# is used to get the specified members of the current Type.

Syntax

Following is the syntax −

public System.Reflection.MemberInfo[] GetMember (string name);
public virtual System.Reflection.MemberInfo[] GetMember (string name, System.Reflection.BindingFlags bindingAttr);

Example

Let us now see an example to implement the Type.GetMember() method −

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.GetMember("SubName");
         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 SubName
FieldInfo = System.String SubName

Example

Let us now see another example to implement the Type.GetMember(String, BindingFlags) method −

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.GetMember("SubName", 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 SubName
FieldInfo = System.String SubName

Updated on: 11-Nov-2019

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements