Linq: transform memberExpression type to not nullable

c#, linq, nullable

Solution

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

Problem

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?

Original source