Type.GetField() Method in C#


The Type.GetField() method in C# is used to get a specific field of the current Type.

Syntax

Following is the syntax −

public System.Reflection.FieldInfo GetField (string name);
public abstract System.Reflection.FieldInfo GetField (string name, System.Reflection.BindingFlags bindingAttr);

Above, the name is the string containing the name of the data field to get. The bindingAttr parameter is the bitwise combination of the enumeration values that specify how the search is conducted.

Example

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

using System;
using System.Reflection;
public class Demo {
   public static void Main(){
      Type type = typeof(Subject);
      try {
         FieldInfo fieldInfo = type.GetField("SubName");
         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 −

FieldInfo = System.String SubName

Example

Let us now see another example to implement the Type.GetField() method −

using System;
using System.Reflection;
public class Demo {
   public static void Main(){
      Type type = typeof(Subject);
      try {
         FieldInfo fieldInfo = type.GetField(null);
         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 −

System.ArgumentNullException
raja
Published on 06-Nov-2019 07:12:04
Advertisements