So I know what Expression.DebugInfo is used for, and I have an Debug expression created, but how to I tag other expressions with this debug info? Here's what I'm trying as a really basic test:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
namespace ExpressionDebugTest
{
class Program
{
static void Main(string[] args)
{
var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("foo"), System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave);
var mod = asm.DefineDynamicModule("mymod", true);
var type = mod.DefineType("baz", TypeAttributes.Public);
var meth = type.DefineMethod("go", MethodAttributes.Public | MethodAttributes.Static);
var sdi = Expression.SymbolDocument("TestDebug.txt");
var di = Expression.DebugInfo(sdi, 2, 2, 2, 12);
var exp = Expression.Divide(Expression.Constant(2), Expression.Subtract(Expression.Constant(4), Expression.Constant(4)));
var block = Expression.Block(di, exp);
Expression.Lambda(block, new ParameterExpression[0]).CompileToMethod(meth);
var newtype = type.CreateType();
asm.Save("tmp.dll");
newtype.GetMethod("go").Invoke(null, new object[0]);
//meth.Invoke(null, new object[0]);
//lambda.DynamicInvoke(new object[0]);
Console.WriteLine(" ");
}
}
}
I know Debug info only works for compiled methods so that's why I'm generating an assembly on the fly. But when this code causes a "divide by zero" error, it's not showing my my "TestDebug.txt" file
So it seems I was missing the debug info generator. This code needed to be added:
var gen = DebugInfoGenerator.CreatePdbGenerator();
Expression.Lambda(block, new ParameterExpression[0]).CompileToMethod(meth,gen);
It works like a charm now!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With