FieldInfo Class

Microsoft.DotNet.Common.Reflection
Represents field information and provides access to field metadata. This class allows you to discover, inspect, and potentially manipulate the fields of a type at runtime.

Syntax

public abstract class FieldInfo : MemberInfo

Inheritance

Members

Methods

  • object GetValue(object obj)

    Returns the value of the specified field on the specified object. For static fields, the obj parameter is ignored.

  • void SetValue(object obj, object value)

    Sets the value of the specified field on the specified object. For static fields, the obj parameter is ignored.

  • void SetValueDirect(object obj, object value)

    Sets the value of the specified field on the specified object, possibly with a different type than the field's declared type.

  • object GetRawConstantValue()

    Returns the value of the specified field. This method applies only to fields that have a compile-time constant value.

Properties

  • FieldAttributes Attributes { get; }

    Gets the attributes associated with this field.

  • Type FieldType { get; }

    Gets the Type of the field.

  • bool IsAssembly { get; }

    Returns true if the field is visible to the assembly, and false otherwise.

  • bool IsFamily { get; }

    Returns true if the field is visible only to members of the class and its derived classes, and false otherwise.

  • bool IsFamilyAndAssembly { get; }

    Returns true if the field is visible only to members of the class and its derived classes, and to all assemblies with the same owner, and false otherwise.

  • bool IsFamilyOrAssembly { get; }

    Returns true if the field is visible only to members of the class and its derived classes, or to all assemblies with the same owner, and false otherwise.

  • bool IsInitOnly { get; }

    Returns true if the field can be written to only during the constructor invocation, and false otherwise.

  • bool IsLiteral { get; }

    Returns true if the field is a compile-time constant, and false otherwise.

  • bool IsPrivate { get; }

    Returns true if the field is private, and false otherwise.

  • bool IsPublic { get; }

    Returns true if the field is public, and false otherwise.

  • bool IsSpecialName { get; }

    Returns true if the field is a special name, and false otherwise.

  • bool IsStatic { get; }

    Returns true if the field is static, and false otherwise.

Example

// Assuming 'myObject' is an instance of a class with a public field named 'myField' // and 'MyClass' is the type of 'myObject'. Type myType = typeof(MyClass); FieldInfo myFieldInfo = myType.GetField("myField", BindingFlags.Instance | BindingFlags.Public); if (myFieldInfo != null) { object fieldValue = myFieldInfo.GetValue(myObject); Console.WriteLine($"The value of myField is: {fieldValue}"); // To set the value (if not readonly or constant) // myFieldInfo.SetValue(myObject, newValue); }

See Also