FieldBuilder Class

Namespace: System.Reflection.Emit
Assembly: mscorlib (in mscorlib.dll)

Summary

Represents a field in a TypeBuilder. The FieldBuilder class allows you to define the name, attributes, and type of the field. It is used in conjunction with the TypeBuilder class to dynamically create types at runtime.

Syntax

public sealed class FieldBuilder : FieldInfo

Constructors

Methods

Properties

Remarks

The FieldBuilder class is part of the System.Reflection.Emit namespace, which provides types that allow you to create an assembly in a subdirectory of the current directory, a new assembly in memory, or a stream in memory.

Fields are defined on a TypeBuilder object using the TypeBuilder.DefineField method. This method returns a FieldBuilder instance.

You can then use the methods of FieldBuilder to set its constant value, custom attributes, and offset.

Example

// Example demonstrating the use of FieldBuilder using System; using System.Reflection; using System.Reflection.Emit; public class DynamicTypeGenerator { public static Type CreateDynamicTypeWithField() { AssemblyName assemblyName = new AssemblyName("MyDynamicAssembly"); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule"); TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicClass"); // Define a string field named 'Message' FieldBuilder fieldBuilder = typeBuilder.DefineField("Message", typeof(string), FieldAttributes.Public); // Set a constant value for the field fieldBuilder.SetConstant("Hello from dynamic field!"); // Define a constructor MethodBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes); ILGenerator constructorIL = constructorBuilder.GetILGenerator(); constructorIL.Emit(OpCodes.Ldarg_0); constructorIL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); constructorIL.Emit(OpCodes.Ret); return typeBuilder.CreateType(); } public static void Main(string[] args) { Type dynamicType = CreateDynamicTypeWithField(); object instance = Activator.CreateInstance(dynamicType); FieldInfo messageField = dynamicType.GetField("Message"); if (messageField != null) { object value = messageField.GetValue(instance); Console.WriteLine($"Field 'Message' value: {value}"); } } }