Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetType case insensitive - WinRT

From microsoft documentation, Type.GetType can be case-insensitive in .NET 4.5. Unfortunately, this is not available in WinRT (Metro/Modern UI/Store apps).

Is there a known workaround ? Because I have to instantiate objects from a protocol which have all the string representations in uppercase.

Example : from "MYOBJECT", I have to instantiate MyObject.

I currently use Activator.CreateInstance(Type.GetType("MYOBJECT")), but due to the case sensitivity, it does'nt work.

Thanks

like image 820
Nicolas Voron Avatar asked Oct 26 '12 14:10

Nicolas Voron


1 Answers

Do you know the assembly you're loading the types from? If so, you could just create a case-insensitive Dictionary<string, Type> (using StringComparer.OrdinalIgnoreCase) by calling Assembly.GetTypes() once. Then you don't need to use Type.GetType() at all - just consult the dictionary:

// You'd probably do this once and cache it, of course...
var typeMap = someAssembly.GetTypes()
                          .ToDictionary(t => t.FullName, t => t,
                                        StringComparer.OrdinalIgnoreCase);

...

Type type;
if (typeMap.TryGetValue(name, out type))
{
    ...
}
else
{
    // Type not found
}

EDIT: Having seen that these are all in the same namespace, you can easily filter that :

var typeMap = someAssembly.GetTypes()
                          .Where(t => t.Namespace == "Foo.Bar")
                          .ToDictionary(t => t.Name, t => t,
                                        StringComparer.OrdinalIgnoreCase);
like image 80
Jon Skeet Avatar answered Oct 13 '22 08:10

Jon Skeet