Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constant evaluation of Nullable<T>.HasValue fails with System.Reflection.TargetException: Non-static method requires a target when null. #3272

Closed
ccurrens opened this issue Jun 16, 2022 · 0 comments · Fixed by #3273

Comments

@ccurrens
Copy link
Contributor

Describe the bug
Constant evaluation of Nullable<T>.HasValue fails with System.Reflection.TargetException: Non-static method requires a target when null.

To Reproduce
Create a linq query with a Nullable<T> closure whose value is null, with a call to HasValue in it.

using Microsoft.Azure.Cosmos;

const string account = "https://localhost:8081";
const string key = "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";

using var client = new CosmosClient(account, key);
var container = client.GetContainer("NotEven", "MakingARequest");

bool? check = null;
var linq = container.GetItemLinqQueryable<Test>().Where(a => check.HasValue && a.Okay == check);
Console.WriteLine(linq.ToString());

class Test
{
    public bool Okay { get; set; }
}

Expected behavior
The query would output true if the constant was non-null or false, if it was null.

Actual behavior
A System.Reflection.TargetException is thrown.

Environment summary
SDK Version: 3.27.0+
OS Version (e.g. Windows, Linux, MacOSX): OS independent

Additional context
This was introduced with #2924, which added a performance boost in evaluating constant members. This works well for most types, except for Nullable<T> which has special run-time behaviors that make it very difficult to use with reflection. Nearly all reflection calls use object as parameter (like PropertyInfo.GetValue(object obj)), which requires boxing of struct values. Nullable<T> have special behavior in the runtime where they the nullable itself is not boxed, but rather the value of it is. This results in passing null (rather than a Nullable<T> with no value) to PropertyInfo.GetValue, which throws the exception because it's an instance method without a valid target.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant