Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type in referenced assembly by supplying class name as string?

These are similar questions: How-to: Load a type from a referenced assembly at runtime using a string in Silverlight, GetType on a class in a referenced assembly fails but neither answer works.

I've got an MVC project that pulls data from a database that includes the plain types as strings. These types are in a referenced assembly, not in the MVC project.

So for example let's say my Referenced Assembly Name is MyFramework and the plain type name Car, the full type name could be MyFramework.Cars.Car or MyFramework.Vehicles.Cars.Car or some other variation. All I have are the referenced assembly name and plain class name as strings. How can I get the type regardless of the full type name?

Finally, could I write a function in the referenced assembly that calls GetType() and use that in the MvC project so I could forego including the assembly name? I want to remove knowing the assembly name so I thought I could write a Util IN the referenced assembly like:

namespace MyFramework //the referenced assembly
{
  public static class TypeUtil
  {
    public static Type GetFrameworkType(string typeName)
    {
        return Type.GetType(typeName);
    }
  }
}

And then in my MVC project I could call it without needing the assembly as a string name. Is that possible or will I always need the assembly name?

like image 395
SventoryMang Avatar asked Aug 16 '12 19:08

SventoryMang


People also ask

How do you get type objects from assemblies that are already loaded?

Use Type. GetType to get the Type objects from an assembly that is already loaded.

How to Get type of assembly in C#?

GetType(String, Boolean, Boolean) Gets the Type object with the specified name in the assembly instance, with the options of ignoring the case, and of throwing an exception if the type is not found.

What is GetType () name in C#?

The GetType() method of array class in C# gets the Type of the current instance. To get the type. Type tp = value. GetType(); In the below example, we are checking the int value using the type.


1 Answers

Maybe the referenced assembly isn't loaded at the time. Also, I understand from your question that you do not have the full type name, only the class name.
You should try something along this line then:

Type type = Assembly.Load("YourAssemblyName").GetTypes().First(t => t.Name == "ShortTypeName");

Hope I understood you correctly.

like image 172
Jony Adamit Avatar answered Sep 21 '22 16:09

Jony Adamit