0

I'm trying to call

Type.GetType("System.Diagnostics.TraceFilter")

not typeof(System.Diagnostics.TraceFilter)

but the result is always null. Could anyone help me out? How to get class type for this abstract class?

4 Answers 4

6

From the documentation for Type.GetType(string typeName)

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

The type you are fishing around for (i.e. "System.Diagnostics.TraceFilter") is not in the currently executing assembly or in "Mscorlib.dll", it is in fact in "System.dll". Therefore you have to use the fully qualified assembly name, e.g.:

 Type type = Type.GetType("System.Diagnostics.TraceFilter, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

Alternatively you can use:

 Type type = typeof(System.Diagnostics.TraceFilter);
2

It's probably because you must provide an assembly-qualified name.

Better, though, would be to use this instead:

typeof(System.Diagnostics.TraceFilter)
2
  • The idea is getting Type object of any classes. I would like to use reflection in this case. Its assembly is System. Thus, by default Type.GetType should understand where it is. Jul 31, 2010 at 15:47
  • Can you explain what the more general problem you are trying to solve is? There may be a way to use typeof() and generics instead of strings.
    – siride
    Jul 31, 2010 at 15:56
1

According to MSDN, Type.GetType(string) requires an assembly-qualified name unless the target type is either in the currently executing assembly or mscorlib.dll. System.Diagnostics.TraceFilter is in System.dll, which means that you must use an assembly-qualified name.

0

Sometimes even if the right assembly is loaded you can't use reflection as you might expect. It often happens when using injection frameworks like MEF or Unity. If typeof() operator is not an option and Type.GetType() fails then this function usually does the trick:

public static Type GetTypeEx(string fullTypeName)
{
 Type type = Type.GetType(fullTypeName);
 if (type != null)
     return type;

 foreach (System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
 {
     Type t2 = assembly.GetType(fullTypeName);
     if (t2 != null)
         return t2;
 }
 return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.