36
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?

gdoron
  • 147,333
  • 58
  • 291
  • 367
NIlesh Lanke
  • 1,213
  • 9
  • 26
  • 35
  • 4
    do you realize that you could have multiple different classes called TheClass in a project where many references have been added and the file where you try to resolve the type has many using statements? You should pass the fully qualified name including namespace like when you reference yourself in a document you write First name and Last name. Which of many TheClass classes should the compiler use in case of many present? Namespace tells which one. – Davide Piras Feb 14 '12 at 08:20
  • I would throw `ArgumentException` instead of just return `null`. You can't distinguish without `Namespace` – gdoron Feb 14 '12 at 08:26
  • possible duplicate of [Getting a System.Type from type's partial name](http://stackoverflow.com/questions/179102/getting-a-system-type-from-types-partial-name) – nawfal Aug 19 '14 at 07:35

4 Answers4

58

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();
}
Fr33dan
  • 4,227
  • 3
  • 35
  • 62
23

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.

tocqueville
  • 5,270
  • 2
  • 40
  • 54
0

Simple Cached version

Do this once....

        nameTypeLookup = typeof(AnyTypeWithin_SomeNamespace).Assembly
            .DefinedTypes.Where(t => t.DeclaringType == null)
            .ToDictionary(k => k.Name, v => v);

Usage - lookup many times via dictionary

nameTypeLookup["TheClass"];
CRG
  • 677
  • 1
  • 7
  • 16
  • This is elegant and reusable, and met my usage needs best compared to other answers (which also would've worked). Not sure why you got downvotes, because this a) works and b) is elegant / simple / concise if you want to load Types by their short name rather than the rather lengthy AssemblyQualifiedName, and you want to scope within your own specific assembly by anchoring to a known type that won't go away, such as the main table/entity in your ORM/EM. – Tim Apr 27 '21 at 15:54
  • 1
    Additionally, in my implementation of your answer, I can just say `this.GetType().Assembly...` without grabbing some other type, as my class that refers to other classes by short name is in the same assembly as the target classes. `return this.GetType().Assembly.DefinedTypes.First(t => t.Name == ClassName);` – Tim Apr 27 '21 at 17:46
-6

That's the parameter the method expect to get, so no. You can not.

typeName: type name qualified by its namespace.

MSDN

How do you expect to distinguish between two classes with the same name but different Namespace?

namespace one
{
    public class TheClass
    {
    }
}

namespace two
{
    public class TheClass
    {
    }
}

Type.GetType("TheClass") // Which?!
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • According to my need there is no situation like this. – NIlesh Lanke Feb 14 '12 at 08:27
  • According to my need there will not be any situation like this.So in that case how can i go about it? – NIlesh Lanke Feb 14 '12 at 08:27
  • 4
    @NIleshLanke, I hope you realize that Microsoft didn't design the .NET framework according to **your** needs but it was architected to be used in a much more broader scenarios. Like for example a scenario where you have the same class name in two different namespaces. – Darin Dimitrov Feb 14 '12 at 08:45
  • @DarinDimitrov. +1. Though it could return that type if it finds that there is only one type in the assembly. – gdoron Feb 14 '12 at 08:47
  • @NIleshLanke. Are you still having difficulties? – gdoron Feb 14 '12 at 20:55
  • 2
    @gdoron, why the insistence in this post that it can't be don't when the accepted answer is showing that it can be? –  Jul 11 '15 at 17:32
  • 1
    @abc, "Avoid giving namespace name in Type.GetType()" that's the answer, if you want to use `Type.GetType` you have to pass the namespace. – gdoron Jul 12 '15 at 01:03
  • 3
    @gdoron, No, you don't. The answer above literally shows you how to do it. –  Jul 24 '15 at 21:25
  • @gdoron, Even though the correct answer might be bad practice, it can still be done. – Bracher Jun 27 '16 at 14:02
  • 1
    @Bracher, no, he didn't ask how he can get the Type of class without a namespace, he asked _"Avoid giving namespace name in Type.GetType()"_, and the answer is **you can NOT**. You can implement something else, but it won't bloody be `Type.GetType()`. – gdoron Jun 27 '16 at 14:21
  • 9
    @gdoron, You need to look at what the user is actually after and not just the literal meaning of the question title. Its like me asking if I can drink a watermelon and you just replying "you can NOT", but then Fr33dan comes along and says "You can if you dice it up and throw it in a Nutribullet" - which is what I'm actually after. I think it is safe to say the user in this case just wanted some way to get the type without having to specify the namespace. – Bracher Jun 27 '16 at 15:46
  • 4
    @gdoron, read this http://stackoverflow.com/help/how-to-answer especially the section regarding "Answer the question" – Bracher Jul 18 '16 at 07:22