Javatpoint Logo
Javatpoint Logo

Type.GetField() Method in C#

In this article, we will discuss the Type.GetField() method in C# with its syntax and examples.

What is the Type.GetField() Method?

The Type.GetField() function returns a specified public field of a type. It accepts the field name as an input, and if the field is discovered, it produces a FieldInfo object representing that field; otherwise, it returns null. This technique enables dynamic access to fields by their given names during runtime, enabling reflection-based activities such as reading or updating field values and retrieving metadata about the field, such as its type or attributes. It is particularly useful for situations where field access must be determined dynamically or when evaluating and changing types and their members at runtime.

Type.GetFields() method is utilized to retrieve the fields of the current Type. This method's overload list contains the following two methods:

  • GetFields() Method
  • GetFields(BindingFlags) Method

Syntax:

It has the following syntax:

Return value: This function generates an array of FieldInfo objects expressing all of the public fields declared for the current Type. If there are no public fields declared for the current Type, an empty array of type FieldInfo is returned.

Example 1:

Let us take a program to illustrate the Type.GetFields() method in C#.

Output:

The Fields of the current type are as Follows: System.Int32 idNum

Example 2:

Let us take another example to illustrate the Type.GetFields() method in C#.

Output:

The Public Fields of the current type is as follow: There were no public fields.

GetFields(BindingFlags) method

The GetFields(BindingFlags) method is used to return the global field defined on the module, which matches the defined binding flags.

Syntax:

It has the following syntax:

Here, bindingAttr is a bitmask consisting of one or more BindingFlags that describe how the search is performed or Zero to return null.

Return Value:

This function provides an array of FieldInfo objects containing all fields declared for the current Type that fulfill the set of binding requirements. If no fields are declared for the current Type, or neither of the defined fields fulfill the binding criteria, a blank array of type FieldInfo is returned.

Example:

Let us take an example to illustrate the Type.GetFields(Binding) method in C#.

Output:

The FieldInfo is - System.String Name






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA