Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Guid NOT an object in c#?

I just got the following exception, which seems to indicate that Guid is not an object.

Expression of type 'System.Guid' cannot be used for return type 'System.Object'

How is Guid not an object?

And how does the compiler figure this out? There must be something that would allow me to detect at runtime when a type is not an object, if so what would this be?

====================Edit with additional info====================

Expression.Lambda<Func<object>>(SomeExpression)

Where SomeExpression could be a constant value of a Guid, for all that matters.

like image 602
Alwyn Avatar asked Feb 26 '13 08:02

Alwyn


1 Answers

Expression.Lambda<Func<object>>(SomeExpression)

The problem here is that you are using expression trees incorrectly. Even though the box operation is implicit in C#, it still exists. It is not implicit in expression trees. The following should fix it:

Expression.Lambda<Func<object>>(
    Expression.Convert(SomeExpression, typeof(object))

You could also check SomeExpression.Type.IsValueType to decide whether or not to add this additional explicit conversion.

like image 190
Marc Gravell Avatar answered Sep 28 '22 15:09

Marc Gravell