Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test if a variable is dynamic?

Tags:

c#

dynamic

The following piece of code will always return true unless the variable v is null:

v is dynamic

and the following test will not compile ("The typeof operator cannot be used on the dynamic type"):

v.GetType() == typeof(dynamic)

So is there a way to test if the variable is dynamic?

like image 779
dav_i Avatar asked Nov 05 '13 09:11

dav_i


People also ask

What is a dynamic variable?

In programming, a dynamic variable is a variable whose address is determined when the program is run. In contrast, a static variable has memory reserved for it at compilation time.

What is a dynamic variable example?

Dynamic Variable Overview The distinguishing characteristic of a dynamic variable is that its value can change while the application runs. For example, your application might maintain a threshold value that is compared to a field value in each tuple processed.

How can you tell if a dynamic object is null?

All dynamic means is "I don't know the type until runtime". If it doesn't override ToString , then it's calling object. ToString() which returns the fully qualified name of the type of the Object - so yes - the . ToString() == null check is not required.


3 Answers

Firstly, you need to separate the variable and the object. A variable is dynamic if it is defined as dynamic. That is all. There is nothing more. A field or property would be annotated with the [Dynamic] attribute, i.e.

public dynamic Foo {get;set;}

is actually:

[Dynamic]
public object Foo {get;set;}

This basically acts as a prompt for the compiler to access the object via the dynamic API rather than via the OOP API.

An object supports full dynamic capabilities if it implements IDynamicMetaObjectProvider - however, such an object can be accessed via both the dynamic API and via the regular OOP API (it can have both). Equally, an object that doesn't implement IDynamicMetaObjectProvider can be accessed via either API (but: only the public members will be available via dynamic).

like image 87
Marc Gravell Avatar answered Oct 24 '22 09:10

Marc Gravell


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.

But You can check if an instance is of type IDynamicMetaObjectProvider or you can check whether the type implements IDynamicMetaObjectProvider

like image 23
Krzysztof Cieslak Avatar answered Oct 24 '22 09:10

Krzysztof Cieslak


In C# dynamic means no complile-time check and it's gonna have the type of the other side of the = symbol. However GetType is a runtime evaluation, so you always gonna retrieve declared type and not dynamic.

You can read a little bit more here: http://msdn.microsoft.com/en-us/magazine/gg598922.aspx

like image 2
Andras Sebo Avatar answered Oct 24 '22 08:10

Andras Sebo