31

I would like to get the Type for an dynamic object, something like:

dynamic tmp = Activator.CreateInstance(assembly, nmspace + "." + typeName);
Type unknown = tmp.GetType();

Except that in the above, GetType() returns the type of the wrapper for dynamic objects not the type of the wrapped object. Thanks!

Radu M.
  • 1,271
  • 2
  • 14
  • 19

2 Answers2

34

You need to do this...

Type unknown = ((ObjectHandle)tmp).Unwrap().GetType();

By the way, this is a little confusing because if you call Activator.CreateInstance on a type in your current assembly...

Activator.CreateInstance(typeof(Foo))

...the object is not wrapped and the original code works fine.

Eric Farr
  • 2,683
  • 21
  • 30
  • 1
    btw, it does this to prevent the assembly being loaded into the current appdomain needlessly. When you unwrap, it will be loaded. – x0n Dec 31 '13 at 15:22
  • ObjectHandle? You do realize .NET Remoting is deprecated... and will never exist in .NET Core! – Latency Jun 26 '20 at 18:35
  • @Latency The answer is from 2011, they obviously didn't and couldn't have anticipated a framework that would have came out years later. – b.pell Oct 16 '20 at 15:38
  • Oh, yeah.. you are right! I overlooked the date on this post and assumed it was from this year. – Latency Oct 18 '20 at 17:55
  • Not working in my case. In framework 4.8 anyhow `dynamic` is NOT castable to `ObjectHandle` it gives the following error : `{"Cannot convert type 'System.__ComObject' to 'System.Runtime.Remoting.ObjectHandle'"}` – Franck Dec 01 '21 at 14:04
2

If you can use Activator.CreateInstance, you can directly use:

object tmp = Activator.CreateInstance(assembly, nmspace + "." + typeName);
Type unknown = tmp.GetType();
unruledboy
  • 2,455
  • 2
  • 23
  • 30