4

I have a C# method which creates a new instance of a class from a string, however, I get an error when running the code.

obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));

ArgumentNullException was unhandled

Value cannot be null

Parameter name: type

Any help on this error would be appreciated.

7 Answers7

5

You may need to use the assembly qualified name as the argument to Type.GetType

eg AssemblyName.Namespace.ClassName

MSDN Doc on assembly qualified names

Amal Sirisena
  • 1,479
  • 10
  • 10
  • The FQTN is Namespace.Class,Assembly i.e. the assembly name goes at the end and is separated by a comma (not at the front and separated by a dot). – itowlson Feb 20 '10 at 00:04
  • Thanks. I had to put `Namespace.className` –  Feb 20 '10 at 00:05
  • @Tim Cooper - No problem, glad to help @itowlson - Thanks, I have updated my answer to correct my terminology. – Amal Sirisena Feb 20 '10 at 00:10
3

You may just be missing the namespace from the classname

zincorp
  • 3,284
  • 1
  • 15
  • 18
1

Works for me:

class ClassX {}
class classPrefix_x : ClassX {}

public class Program
{
    public static void Main()
    {
        string className = "x";
        ClassX obj = (ClassX)Activator.CreateInstance(Type.GetType("classPrefix_" + className));
        Console.WriteLine(obj);
    }
}

Result:

classPrefix_x

The class you are looking for must not be defined. Are you sure you typed it correctly?

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

It looks like your Type.GetType("classPrefix_" + className) call is returning a null. This is causing the ArgumentNullException when passed to the CreateInstance method.

Evaluate "classPrefix_" + className and check that you do have a type called what it evaluates to.

You also should be specifying the AssemblyQualifiedName when using the Type.GetType method (ie. the fully qualified type name including the assembly name and namespace).

adrianbanks
  • 81,306
  • 22
  • 176
  • 206
0

You probably don't have a type of "classPrefix_" plus whatever you have on className. The Type.GetType() call returns null and CreateInstance throws the ArgumentNullException.

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
0

This is because the Type.GetType(classHere) didn't find anything, are you sure that the classname you're after exists? Remember it should be prefixed with a namespace if possible, and won't be found in an external assembly unless it's already loaded in the App domain.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
0

It looks like Type.GetType("classPrefix_" + className) is returning null.

This returns null when it cannot find the type. A couple of possible causes are missing namespace, or the assembly the class is in is not loaded yet.

The Api documentation on the method which may give some more insite. http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

aaronb
  • 2,149
  • 15
  • 8