the following member expression type can sometimes be NUllable, I m checking that , however I need to convert it to a non nullable type ,
MemberExpression member = Expression.Property(param, something);
var membertype = member.Type;
if (membertype.IsGenericType && membertype.GetGenericTypeDefinition() == typeof(Nullable<>))
{ // convert to not nullable type?...
Does anyone know how?
You can use Nullable.GetUnderlyingType
to check (more simply) for Nullable<T>
, and just use GetValueOrDefault
- like below (I've only included the Func<Foo,int>
etc as demo):
using System;
using System.Linq.Expressions;
class Foo {
public int? Bar { get; set; }
static void Main() {
var param = Expression.Parameter(typeof(Foo), "foo");
Expression member = Expression.PropertyOrField(param, "Bar");
Type typeIfNullable = Nullable.GetUnderlyingType(member.Type);
if (typeIfNullable != null) {
member = Expression.Call(member,"GetValueOrDefault",Type.EmptyTypes);
}
var body = Expression.Lambda<Func<Foo, int>>(member, param);
var func = body.Compile();
int result1 = func(new Foo { Bar = 123 }),
result2 = func(new Foo { Bar = null });
}
}
This is just a guess, but could you use Nullable.GetValueOrDefault? I am not sure if the return type would be correct.
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