Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# How to use GetType in a dynamic object?

I have a dynamic an I need to find its type to use the type name. The only thing I
‘m sure in this point of the code is that the dynamic object is from a custom class.

I want to avoid to make multiple checks with if.
I tried GetType and typeof, but no success.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The only thing I ‘m sure in this point of the code is that the dynamic object is from a custom class.

Assuming you mean a simple POCO that is exposed via dynamic, then forget about the dynamic completely:

var obj = (object)yourDynamicThing;
var type = obj.GetType();
// from here: reflection and/or type tests all the way down

In the more general case (where you don’t know anything about the instance): reflection (GetType()) and dynamic are two completely different models; the type of the dynamic is irrelevant and will often be a private implementation type (DapperRow, for example) or the simple ExpandoObject. Asking what the type is: is not a reasonable question.

Knowing the type won’t help you much if the type is a IDynamicMetaObjectProvider, i.e. implements dynamic in a bespoke way.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading