Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Type.GetFields() Method
Next article icon

C# | Type.GetField() Method

Last Updated : 10 Dec, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Type.GetField() Method is used to get a specific field of the current Type. There are 2 methods in the overload list of this method as follows:

  • GetField(String) Method
  • GetField(String, BindingFlags) Method

GetField(String) Method

This method is used to search for the public field with the specified name.

Syntax: public System.Reflection.FieldInfo GetField (string name);
Here, it takes the string containing the name of the data field to get.

Return Value: This method returns an object representing the public field with the specified name if found otherwise, null.

Exception: This method throws ArgumentNullException if the name is null .

Below programs illustrate the use of Type.GetField() Method:

Example 1:




// C# program to demonstrate the
// Type.GetField(String) Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing object of Type
        Type objType = typeof(Student);
  
        // try-catch block for handling Exception
        try {
  
            // Getting FieldInfo by
            // using GetField(String) Method
            FieldInfo info = objType.GetField("Name");
  
            // Display the Result
            Console.WriteLine("FieldInfo is: {0}", info);
        }
  
        // catch ArgumentNullException here
        catch (ArgumentNullException e) 
        {
            Console.Write("name is null.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
  
// Defining class Student
public class Student 
{
    public string Name = "Rahul";
    public string Dept = "Electrical";
    public int Roll = 10;
}
 
 
Output:
  FieldInfo is: System.String Name  

Example 2: For ArgumentNullException




// C# program to demonstrate the
// Type.GetField(String) Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing object of Type
        Type objType = typeof(Student);
  
        // try-catch block for handling Exception
        try {
  
            // Getting FieldInfo by
            // using GetField() Method
            FieldInfo info = objType.GetField(null);
  
            // Display the Result
            Console.WriteLine("FieldInfo is: {0}", info);
        }
  
        // catch ArgumentNullException here
        catch (ArgumentNullException e)
        {
            Console.WriteLine("Name is null.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
  
// Defining class Student
public class Student 
{
    public string Name = "Rahul";
    public string Dept = "Electrical";
    public int Roll = 10;
}
 
 
Output:
  name is null.  Exception Thrown: System.ArgumentNullException  

GetField(String, BindingFlags) Method

This method is used to search for the specified field, using the specified binding constraints.

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

Parameters:

name: The string containing the name of the data field to get.
bindingAttr: It is a bitmask comprised of one or more BindingFlags that specify how the search is conducted or Zero, to return null.

Return Value: This method returns an object representing the field that matches the specified requirements if found otherwise, null.

Exception: This method throws ArgumentNullException if name is null.

Below programs illustrate the use of the above-discussed method:

Example 1:




// C# program to demonstrate the
// Type.GetField(String) Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing object of Type
        Type objType = typeof(Student);
  
        // try-catch block for handling Exception
        try {
  
            // You must specify either BindingFlags.Instance
            // or BindingFlags.Static
            // and Specify BindingFlags.Public
            // to include public fields in the search
            BindingFlags battr = BindingFlags.Public | BindingFlags.Instance;
  
            // Getting FieldInfo by
            // using GetField() Method
            FieldInfo info = objType.GetField("Name", battr);
  
            // Display the Result
            Console.WriteLine("FieldInfo is: {0}", info);
        }
  
        // catch ArgumentNullException here
        catch (ArgumentNullException e) 
       {
            Console.Write("name is null.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
  
// Defining class Student
public class Student 
{
    public string Name = "Rahul";
    public string Dept = "Electrical";
    public int Roll = 10;
}
 
 
Output:
  FieldInfo is: System.String Name  

Example 2: For ArgumentNullException




// C# program to demonstrate the
// Type.GetField(String) Method
using System;
using System.Globalization;
using System.Reflection;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // Declaring and initializing object of Type
        Type objType = typeof(Student);
  
        // try-catch block for handling Exception
        try {
  
            // You must specify either BindingFlags.Instance 
            // or BindingFlags.Static
            // and Specify BindingFlags.Public
            // to include public fields in the search
            BindingFlags battr = BindingFlags.Public | BindingFlags.Instance;
  
            // Getting FieldInfo by
            // using GetField() Method
            FieldInfo info = objType.GetField(null, battr);
  
            // Display the Result
            Console.WriteLine("FieldInfo is: {0}", info);
        }
  
        // catch ArgumentNullException here
        catch (ArgumentNullException e) 
        {
            Console.WriteLine("name is null.");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
  
// Defining class Student
public class Student 
{
    public string Name = "Rahul";
    public string Dept = "Electrical";
    public int Roll = 10;
}
 
 

Output:

  name is null.  Exception Thrown: System.ArgumentNullException  

Reference:

  • https://docs.microsoft.com/en-us/dotnet/api/system.type.getfield?view=netframework-4.8


Next Article
C# | Type.GetFields() Method

R

RohitPrasad3
Improve
Article Tags :
  • C#
  • CSharp-method
  • CSharp-Type-Class

Similar Reads

  • C# | Type.GetFields() Method
    Type.GetFields() Method is used to get the fields of the current Type. There are 2 methods in the overload list of this method as follows: GetFields() Method GetFields(BindingFlags) Method GetFields() Method This method is used to return all the public fields of the current Type. Syntax: public Syst
    5 min read
  • C# | Type.GetMethods() Method
    Type.GetMethods() Method is used to get the methods of the current Type. There are 2 methods in the overload list of this method as follows: GetMethods(BindingFlags) Method GetMethods() Method GetMethods(BindingFlags) Method This method is used to search for the methods defined for the current Type,
    5 min read
  • C# | Type.GetTypeCode() Method
    Type.GetTypeCode() Method is used to get the underlying type code of the specified Type. Syntax: public static TypeCode GetTypeCode (Type type); Here, it takes the type whose underlying type code to get. Return Value: This method returns the code of the underlying type, or Empty if type is null. Bel
    2 min read
  • C# | Type.GetMember() Method
    Type.GetMember() Method is used to get the specified members of the current Type. There are 3 methods in the overload list of this method as follows: GetMember(String) Method GetMember(String, BindingFlags) Method GetMember(String, MemberTypes, BindingFlags) Method GetMember(String) Method This meth
    6 min read
  • C# | Type.GetInterface() Method
    Type.GetInterface() Method is used to gets a specific interface implemented or inherited by the current Type. GetInterface(String) Method This method is used to search for the interface with the specified name. Syntax: public Type GetInterface (string name); Here, it takes the string containing the
    4 min read
  • C# | Type.GetMembers() Method
    Type.GetMembers() Method is used to get the members (properties, methods, fields, events, and so on) of the current Type. There are 2 methods in the overload list of this method as follows: GetMembers() Method GetMembers(BindingFlags) Method GetMembers() Method This method is used to return all the
    4 min read
  • C# | Type.GetTypeHandle() Method
    Type.GetTypeHandle() Method is used to get the handle for the Type of a specified object. Syntax: public static RuntimeTypeHandle GetTypeHandle (object o); Here, it takes the object for which to get the type handle. Return Value: This method returns The handle for the Type of the specified Object. E
    2 min read
  • C# | Type.GetInterfaces() Method
    Type.GetInterfaces() Method is used to get all the interfaces implemented or inherited by the current Type when overridden in a derived class. Syntax: public abstract Type[] GetInterfaces ();Return Value: This method returns an array of Type objects representing all the interfaces implemented or inh
    2 min read
  • C# | Type.GetProperties() Method
    Type.GetProperties() Method is used to get the properties of the current Type. There are 2 methods in the overload list of this method as follows: GetProperties() Method GetProperties(BindingFlags) Method GetProperties() Method This method is used to return all the public properties of the current T
    5 min read
  • C# | Type.GetNestedType() Method
    Type.GetNestedType() Method is used to get a specific type nested within the current Type. There are 2 methods in the overload list of this method as follows: GetNestedType(String, BindingFlags) Method GetNestedType(String) Method GetNestedType(String, BindingFlags) Method This method is used to sea
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences