Search code examples
c#classreflectionactivator

Create class from string


I'm trying to create a class from its name held in a string. I've tried a bunch of things but always get "Value cannot be null"

Here's the class

public static readonly MigraDoc.DocumentObjectModel.Color Aquamarine
Member of MigraDoc.DocumentObjectModel.Colors

AquaMarine is a class held in MigraDoc.DocumentObjectModel.Colors and is a class of Color

Here's what I tried which is as close as what I thought should work:

Color myColor = (Color)Activator.CreateInstance(Type.GetType("MigraDoc.DocumentObjectModel.Colors+SlateBlue")); 
//+ for nested classes

A variant:

Color myColor = (Color)Activator.CreateInstance(Type.GetType("MigraDoc.DocumentObjectModel+Colors+SlateBlue"));

But I always get:

Value cannot be null.
Parameter name: type

I feel like the solution should not be very far... Any ideas ? :)


Solution

  • No, Aquamarine is not a class, it's a variable. You can't create an instance of a variable...