Activator.CreateInstance(Type) may return null

  • Gérald Barré

Activator.CreateInstance(Type) allows you to create an instance of a type without knowing the type at compile time. For example, you might want to create an instance of a type based on a configuration file or a user input. Anytime you cannot use the new keyword you can use Activator.CreateInstance(Type).

Most people expect this method to return a non-null object as you explicitly ask to create a new instance, but that's not always the case. For Nullable<T> types, Activator.CreateInstance(Type) returns null.

object? value = Activator.CreateInstance(typeof(int?));
Console.WriteLine(value is null); // true

Note that the same applies to calling the constructor using the new keyword:

object? value = new int?();
Console.WriteLine(value is null); // true

You can use the null forgiving operator (!) to suppress the warning that value might be null if you are sure that the type cannot be a Nullable<T>.

// Safe to use the null forgiving operator as we know that the type cannot be a Nullable<T>
object? value = Activator.CreateInstance(typeof(object))!;
Console.WriteLine(value is false); // always true

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub