0

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.

ScubaSteve
  • 7,724
  • 8
  • 52
  • 65

3 Answers3

1

Because you didn't get a return value. the code should be as follows.

string condition = $@"return new List<Guid> {{ new Guid(""{Guid.NewGuid()}""), new Guid(""{id}"") }}.Any(id => id == new Guid(""{id}""));";
Sonsuz
  • 46
  • 3
0

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}""));";

ScubaSteve
  • 7,724
  • 8
  • 52
  • 65
0

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://learn.microsoft.com/en-us/dotnet/csharp/async

Hunter Tran
  • 13,257
  • 2
  • 14
  • 23
  • This is not correct. I was able to access the Result without awaiting and it returned the correct bool value depending on the statement in the eval. As I stated in my answer, the issue was the semi-colon. – ScubaSteve Feb 20 '22 at 01:39