I'm trying to get the field value by using DynamicMethod instead of Reflection. If I change the field fldTest to static, the code works fine but I need also non-static field. When I run the code as below, the System.InvalidProgramException: 'Common Language Runtime detected an invalid program.' occurs. I'm using VS2022, C#10 and Net-6.0
public class Program
{
public string fldTest = "Hello";
public static string GetFldValue(FieldInfo fieldInfo)
{
DynamicMethod _dm = new DynamicMethod("getHello", typeof(string), null, fieldInfo.DeclaringType, true);
ILGenerator _il = _dm.GetILGenerator();
_il.Emit(OpCodes.Nop);
if (fieldInfo.IsStatic)
_il.Emit(OpCodes.Ldsfld, fieldInfo);
else
{
_il.Emit(OpCodes.Ldarg_0);
_il.Emit(OpCodes.Ldfld, fieldInfo);
}
_il.Emit(OpCodes.Ret);
Func<string> _getFieldValue = _dm.CreateDelegate(typeof(Func<string>)) as Func<string>;
string result = _getFieldValue();
return result;
}
public static void Main(string[] args)
{
FieldInfo field = System.Type.GetType("Program").GetField("fldTest");
var x = GetFldValue(field);
Console.WriteLine(x);
Console.ReadKey();
}
}
After many tests, I figured out that a static method can't access a non-static field or property. The reason is because a static method is not associated to a instance. https://education.launchcode.org/csharp-web-development/chapters/classes-part2/instance-and-static-methods.html#static-methods