I am getting this error message for my code: "variable 'assignVal' of type 'System.Int32' referenced from scope '', but it is not defined"
I checked out
- Lambda compilation throws "variable '' of type '' referenced from scope '', but it is not defined"
- variable '' of type '' referenced from scope '', but it is not defined
but unfortunately my sample seems way more simple and still doesn't work for some reason.
This is my code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Threading.Tasks;
using static System.Linq.Expressions.Expression;
namespace ExpressionTests
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine(GetSyncAddExpression()(5) == 6);
Console.ReadKey();
Console.WriteLine(await GetTaskAddExpression()(5) == 6);
Console.ReadKey();
}
private static Func<int, Task<int>> GetTaskAddExpression()
{
var fromResultMethod = typeof(Task).GetMethod(nameof(Task.FromResult)).MakeGenericMethod(typeof(int));
var inParam = Parameter(typeof(int), "p1");
var assignmentValue = Variable(typeof(int), "assignVal");
var retVal = Variable(typeof(Task<int>));
var lambda = Lambda<Func<int, Task<int>>>(Block(
Assign(assignmentValue, Add(inParam, Constant(1))),
Assign(retVal, Call(null, fromResultMethod, assignmentValue)),
retVal
), inParam);
if (Debugger.IsAttached)
Debugger.Break();
return lambda.Compile();
}
private static Func<int, int> GetSyncAddExpression()
{
var inParam = Parameter(typeof(int), "p1");
var assignmentValue = Variable(typeof(int), "assignVal");
var retVal = Variable(typeof(int));
var lambda = Lambda<Func<int, int>>(Block(
Assign(assignmentValue, Add(inParam, Constant(1))),
Assign(retVal, assignmentValue),
retVal
), inParam);
if (Debugger.IsAttached)
Debugger.Break();
return lambda.Compile();
}
}
}
This code sample seems simple enough that it should be working as is and i'm reusing the expressions, so i don't quite understand why i'm getting this error.