Type.GetType case insensitive - WinRT

3.7k Views Asked by At

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

3

There are 3 best solutions below

2
On BEST ANSWER

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);
0
On

You can use GetTypes() method, to fetch all possible types in the assembly where your type is in, after that check which type uppercase equals to your type upper case then use it in GetType method.

0
On

Consider that you actual class name is Car and your query string is CAR. As these are different in terms of case sensitivity, the Type.GetType() will return null. To resolve this first of all filter all the classes from the namespace of Car(Assume that the namespace is Vehicle).

var varClasses = from t in Assembly.GetExecutingAssembly().GetTypes()
                 where t.IsClass && t.Namespace == "Vehicles"
                 select t;

Convert to a List

List<Type> lstClasses = varClasses.ToList();

Declare a variable to get the actual name of the class and use a loop to compare string without case-sensitivity.

string strActualName = "";
foreach (Type t in lstClasses )
{
     if (t.Name.ToLower() == "CAR".ToLower())
     {
           strActualName = t.Name;
           break;
     }
}

Now with the new string, use the Type.GetType()

Type t1 = Type.GetType("Vehicles." + strActualName);