Take the 2-minute tour ×

I'm working with expressions and I need a method which receives an object of some type (currently unknown). Something like this:

public static void Foobar(object Meh) { }

What I need to is make this method return a Nullable<T> version of Meh, but the type T is from Meh.GetType(). So the return would be Nullable<MehType>, where MehType is the type of Meh.

Any ideas or suggestions?


Update: the reason why I needed this is because of this exception:

The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.

return Expression.Equal(leftExpr, rightExpr);

where leftExpr is a System.Nullable1[[System.Int32 and rightExpr is a System.Int32.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

If you don't know the type at compile time, the only way of expressing it is as object - and as soon as you box a nullable value type, you end up with either a null reference, or a boxed non-nullable value type.

So these snippets are exactly equivalent in terms of the results:

int? nullable = 3;
object result = nullable;

int nonNullable = 3;
object result = nonNullable;

In other words, I don't think you can really express what you're trying to do.

share|improve this answer
After reading your, recursive's and FishBasketGordo's obversations, I understand it's impossible to express this. So I got find do it in the other way: make a nullable back to the original type.. inside an expression! –  Ricardo Aug 15 '11 at 21:38

Do you have to use Meh.GetType() instead of a generic? What about this?

public static Nullable<T> Foobar<T>(T Meh) where T : struct { }

I'm making the assumption that "some type" does not mean "any type", because the solution above would only work with value types.

share|improve this answer
Needs a where T : struct constraint. –  Mark H Aug 15 '11 at 21:03
Thanks. I edited that in. –  FishBasketGordo Aug 15 '11 at 21:05
I've tried, but it doesn't work. The type of Meh is object (but it can be a string, Int32 or something else). The error says The type 'object' must be a non-nullable value type in order to use it as paramater 'T' in the generic type or method .... –  Ricardo Aug 15 '11 at 21:09
C# has reference types and value types. In general, reference types live in heap memory and can be null of their own rite, and value types live in stack memory and must have a value, i.e. cannot be null on their own. (There are more subtleties than that, but that's a larger discussion.) That's why we have the Nullable<T> struct, to make value types behave a little bit like reference types. –  FishBasketGordo Aug 15 '11 at 21:15
@ricardo: Nullable<string> cannot exist. Try it out and see! Nullable<T> only is legal for non-nullable types of T. –  recursive Aug 15 '11 at 21:21

Your Answer


