Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a generic parameter is dynamic in .NET 4.0

Tags:

c#

.net-4.0

I have a class ObjectMapper<T> . Is there any way in .NET 4.0 to tell if typeof(T) is dynamic? I want to be able to determine inside a member method whether the class was initialized as new ObjectMapper<dynamic>() vs. new ObjectMapper<SomeConcreteClass>().

like image 541
Dmitry S. Avatar asked Jul 18 '10 21:07

Dmitry S.


People also ask

How do you determine what type a generic parameter T is?

You can get the Type that represents T , and use the IsInterface property: Type type = typeof(T); if (type. IsInterface) { ... } If you want to know which interface is passed, just use == to compare the Type objects, e.g.

How do you find the property of a generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

What is dynamic return type in C#?

C# 4.0 (. NET 4.5) introduced a new type called dynamic that avoids compile-time type checking. A dynamic type escapes type checking at compile-time; instead, it resolves type at run time. A dynamic type variables are defined using the dynamic keyword.

What is generic type parameter in C#?

Generic became part of C# with version 2.0 of the language and the CLR, or Common Language Runtime. It has introduced the concept of type parameters, which allow you to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.


2 Answers

There is no CLR type called dynamic. The C# compiler makes all dynamic values of type object and then calls custom binding code to figure out how to handle them. If dynamic was used, it will show up as Object.

like image 53
Gabe Avatar answered Oct 11 '22 05:10

Gabe


You do this by checking if an instance is of type IDynamicMetaObjectProvider or you can check whether the type implements IDynamicMetaObjectProvider.

like image 26
Steven Avatar answered Oct 11 '22 06:10

Steven