Home > Enterprise >  Roslyn CSharpScript EvaluateAsync Returns False When Statement Should Be True
Roslyn CSharpScript EvaluateAsync Returns False When Statement Should Be True

Time:02-20

I am just learning how to use Roslyn and I have a script like this:

var id = Guid.NewGuid();
string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""));";

var result = CSharpScript.EvaluateAsync<bool>(condition, 
             Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
             .WithImports("System", "System.Collections.Generic", "System.Linq")
             .AddReferences(typeof(System.Linq.Enumerable).Assembly)).Result;

result is coming back as false. I even tried:

var id = Guid.NewGuid();
string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => true);";

It also results in false. I debugged it and grabbed the value in condition and after taking the escaping characters out, it is:

var result = new List<Guid> { new Guid("907eb45d-8646-4b1b-baed-54d451f9753a"),
               new Guid("fef76d20-0066-4ee5-901e-2936c2117a8a") }.Any(id => true);

Which results in true. I'm not sure where I'm going wrong with this.

CodePudding user response:

Not sure why, but the removing the semi-colon at the end of the statement allowed it to return true.

string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""))";

instead of:

string condition = $@"new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""));";

CodePudding user response:

EvaluateAsync is an async function. It will not return data immediately. You will need to put the await keyword before it to wait for the computation.

If you don't, the result variable will init with default value false when you check it before the EvaluateAsync return.

var result = await CSharpScript.EvaluateAsync<bool>(condition, 
             Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
             .WithImports("System", "System.Collections.Generic", "System.Linq")
             .AddReferences(typeof(System.Linq.Enumerable).Assembly)).Result;

You can read more about Asynchronous programming here: https://docs.microsoft.com/en-us/dotnet/csharp/async

  • Related