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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With