Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid giving namespace name in Type.GetType()

Type.GetType("TheClass"); 

Returns null if the namespace is not present like:

Type.GetType("SomeNamespace.TheClass"); // returns a Type object  

Is there any way to avoid giving the namespace name?

like image 202
NIlesh Lanke Avatar asked Feb 14 '12 08:02

NIlesh Lanke


People also ask

What is GetType () name in C#?

GetType or Assembly. GetTypes method to get Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic. If typeName cannot be found, the call to the GetType(String) method returns null .

What is return type of GetType ()?

The gettype() function returns the type of a variable.

How do I use GetType?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.


2 Answers

I've used a helper method that searches all loaded Assemblys for a Type matching the specified name. Even though in my code only one Type result was expected it supports multiple. I verify that only one result is returned every time I used it and suggest you do the same.

/// <summary> /// Gets a all Type instances matching the specified class name with just non-namespace qualified class name. /// </summary> /// <param name="className">Name of the class sought.</param> /// <returns>Types that have the class name specified. They may not be in the same namespace.</returns> public static Type[] getTypeByName(string className) {     List<Type> returnVal = new List<Type>();      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())     {         Type[] assemblyTypes = a.GetTypes();         for (int j = 0; j < assemblyTypes.Length; j++)         {             if (assemblyTypes[j].Name == className)             {                 returnVal.Add(assemblyTypes[j]);             }         }     }      return returnVal.ToArray(); } 
like image 164
Fr33dan Avatar answered Oct 06 '22 00:10

Fr33dan


There is no need to complicate things.

AppDomain.CurrentDomain     .GetAssemblies()     .SelectMany(x => x.GetTypes())     .FirstOrDefault(t => t.Name == "MyTypeName"); 

Use Where instead of FirstOrDefault to get all the results.

like image 26
tocqueville Avatar answered Oct 06 '22 00:10

tocqueville