vezenkov
vezenkov

Reputation: 4145

C# Create an instance of a class from a type FullName

Does anybody know of an easy way to create an instance of a class given the FullName of a type (namespace.classname format), but not having the AssemblyQualifiedName? The FullName of the type is only contained in a single assembly that is referenced and available at runtime, so there is no ambiguity.

I don't have the type, I have a string - the fullname only, without the assembly part. I don't know the assembly, I just know it's referenced and there is only one assembly containing the type fullname.

Thanks!

EDIT: This is to do with deserialization of instances from a proprietary protocol. I've recieved good answers, but what I'll end up do in order to have optimal solution and not iterate through all the assemblies is to create a static dictionary with fullName key and assembly qualified name as value, given I know which exactly are the classes and they are a limited set.

Upvotes: 0

Views: 1533

Answers (2)

John Wu
John Wu

Reputation: 52210

Load all of your assemblies and select over their types, then filter on the name.

public static object CreateType(string typeName)
{
    var allTypes = AppDomain.CurrentDomain
        .GetAssemblies()
        .SelectMany
        (
            a => a.GetTypes()
        );
    var type = allTypes.Single( t => t.Name == typeName );

    return Activator.CreateInstance(type);
}

You might consider adding some validation code to check for duplicates, and to ensure there is a default constructor.

Upvotes: 0

Servy
Servy

Reputation: 203802

You can get all of the active assemblies and then look through each one for a type with the full name you have. You'll need to prepare for the possibility that there are multiple matches, or no matches, among the assemblies.

Upvotes: 3

Related Questions