Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: transform memberExpression type to not nullable

Tags:

c#

linq

nullable

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?

like image 963
roundcrisis Avatar asked Nov 25 '09 16:11

roundcrisis


2 Answers

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 });    
    }
}
like image 107
Marc Gravell Avatar answered Nov 12 '22 11:11

Marc Gravell


This is just a guess, but could you use Nullable.GetValueOrDefault? I am not sure if the return type would be correct.

like image 1
Shawn Avatar answered Nov 12 '22 09:11

Shawn