Get a specific field of the current type C#

CsharpServer Side ProgrammingProgramming

To get a specific field of the current type in C#, 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");
         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 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(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 10-Dec-2019 09:50:28
Advertisements