Home > Mobile >  C# how to cast object to a type returned from GetType()
C# how to cast object to a type returned from GetType()

Time:09-15

// Assuming this object is allocated somewhere else
var dict = new Dictionary<int, string>
{
    {1, "One"},
    {2, "Two"}
};

// allocate a handle for it so it won't get destroyed by GC
var handle1 = GCHandle.Alloc(dict);
// Get internal representation of this object
IntPtr ptrObj = GCHandle.ToIntPtr(handle1);


// Assuming now we are in another module
var handle2 = GCHandle.FromIntPtr(ptrObj); // Get handle from IntPtr of this object
var objDict = handle2.Target; // Get object

// How to convert it back to Dictionary?
// When debug, I know its type is Dictionary<int, string>,
// but how I can know here?
// This conversion is not working
var myDict = (Dictionary<object, object>)objDict;

// Anyway to cast it from GetType()?
var myDict = (objDict.GetType())objDict;

In one module, I created a dictionary and convert to IntPtr (for PInvoke call). In another module, I get the dictionary object from IntPtr, which is a generic object. How can I convert back to it original type so that I can use it like this:

var myDict = (objDict.GetType())objDict; // Assuming this works
var count = myDict.Count; // Get element count

CodePudding user response:

The solution here seems to be to cast as type IDictionary. The Dictionary<TKey, TValue> class implements that interface so it will provide the basic, common functionality regardless of the type of the keys and values.

var handle2 = GCHandle.FromIntPtr(ptrObj);
var myDict = (IDictionary)handle2.Target;

You can then, for instance, pass a key as an object and get a value back as an object:

var value = myDict[key];
  • Related