For various reasons, I need to implement a type caching mechanism in C#. Fortunately, the CLR provides Type.GUID
to uniquely identify a type. Unfortunately, I can't find any way to look up a type based on this GUID. There's Type.GetTypeFromCLSID()
but based on my understanding of the documentation (and experiments) that does something very, very different.
Is there any way to get a type based on its GUID short of looping through all the loaded types and comparing to their GUIDs?
EDIT: I forgot to mention that I would really like a "type fingerprint" of fixed width, that's why the GUID is so appealing to me. In a general case, of course, the fully qualified name of the type would work.
Don't loop to compare. Populate a
Dictionary<Type>
and use theContains
method.This will certainly give you a fixed size entry, since all of them will be object references (instances of Type essentially being factory objects).
The Mono documentation reports that a module has a Metadata heap of guids.
Perhaps Cecil might help you lookup a type based on its guid? Not sure though, there is a GuidHeap class, it seems to be generating the guids though, but perhaps this is enough for your cache to work?
why not use the designated property for that, ie. AssemblyQualifiedName? This property is documented as "can be persisted and later used to load the Type".
The GUID is for COM interop.
This may just be a summary of answers already posted, but I don't think there is a way to do this without first building a map of Guid->Type.
We do this in our framework on initialization:
Handling the AssemblyLoad event takes care of dynamically loaded assemblies.
From what I understand, Type.GUID uses the assembly version of the type as part of the Guid generation algorithm. This may lead to trouble if you increment your assembly version numbers. Using the GetDeterministicGuid method described in another answer would probably be advisable, depending on your application.
What about (from Generating Deterministic GUIDs):
And throw in that
typeof().AssemblyQualifiedName
. You could to store this data inside aDictionary<string, Guid>
collection (or, whatever, a<Guid, string>
).This way you'll have always a same
GUID
for a given type (warning: collision is possible).I would use the typeof (class).GUID to find the instance in the cache dictionary:
and I would have a method to return the dictionary and the GUID as parameter of the method to search for the class in the dictionary.
and I would use a singleton pattern for the cache,
and the call would be something like the code below: