Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.Reflection.FieldInfo: practical reference

System.Reflection.FieldInfo: practical reference: FieldInfo describes a field and can read or set its value through reflection.

Version: .NET API; verified against .NET 10 reference surface

Syntax

System.Reflection.FieldInfo /* select a documented member or constructor */

FieldInfo describes a field and can read or set its value through reflection.

Use it in metadata tools when the field type is not known statically.

SetValue bypasses some compiler checks and is slower than direct access.

For a static field, GetValue and SetValue ignore the target/obj parameter; passing null is conventional, not required. Trimming can remove fields unknown to analysis.

The complete program actually uses System.Reflection.FieldInfo; its exact expected stdout is 8.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var field = typeof(Sample).GetField(nameof(Sample.Value))!;
Console.WriteLine(field.GetValue(new Sample()));

sealed class Sample { public int Value = 8; }

Result

8

The complete program actually uses `System.Reflection.FieldInfo`; its exact expected stdout is `8`.

Sources