Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for typeof(dynamic)?

I've got a generic method TResult Foo<TSource, TResult>(IEnumerable<TSource> source) and if TResult is declared as dynamic I want to execute a different code path than for other type declarations.

For regular types you can do stuff like:

if (typeof(TResult) == typeof(int))
    return ExpressionFactory.CreateExpandoFunction<TSource, TResult>();

But if (typeof(TResult) == typeof(dynamic)) does not compile.

Is there anyway to make this sort of determination at runtime when the method is called with the declaration:

dyanmic x = Foo<int, dynamic>(list);

Since dynamic itself isn't a type what should I be testing for? IDynamicMetaObjectProvider?

EDIT This is part of a SQL text to System.Linq.Expression evaluator. The specific desire to branch if TResult is dynamic is for some pseudo logic that looks something like this:

if (type is struct)
   create selector that initializes each element to result values
else if (type is class)
   create selector that initialize each element to new instance and set member properties
else if (type is dynamic)
   create selector that initializes each element to new `ExpandoObject` and populates/sets member properties
like image 364
dkackman Avatar asked Oct 21 '09 04:10

dkackman


2 Answers

Simply speaking you cannot because there is no type dynamic. In type dynamic is written out as object with a special attribute attached (Dynamic) if the type appears in metadata. Essentially saying typeof(dynamic) is no different than typeof(object) for most purposes.

like image 163
JaredPar Avatar answered Oct 24 '22 22:10

JaredPar


It is not necessary for object declared as dynamic to be some specific type of object. It can be a subclass of DynamicObject (and thus provide specific logic for operations lookup), but it can be a normal object as well (as @JaredPar said).

Maybe, if you explain what sort of branch you want to make for dynamic objects it would be possible to find better solution.

like image 28
elder_george Avatar answered Oct 24 '22 22:10

elder_george