tags:

views:

232

answers:

2

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?

+1  A: 

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

Shawn Simon
Hi, thanks for answering, I need to transform member into basically member but that is not a nullable type, dont actually need the value
Miau
ah ok didnt know you had to use it that way thanks
Miau
+4  A: 

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 });    
    }
}
Marc Gravell
nice, was looking for something like that : )
Shawn Simon