The post Activator.CreateInstance in C# – A Quick Rundown appeared first on Dev Leader.
Activator.CreateInstance
in C# is one of the main tools we have when it comes to reflection in C#. This article is a quick look at how we can leverage Activator.CreateInstance
as a brief primer on using reflection within C#.
What Is Activator.CreateInstance?
Now, let’s explore Activator.CreateInstance
and understand how it enables dynamic object creation. The Activator
class is a part of the System
namespace in C# and provides methods for creating instances of types. The CreateInstance
method specifically allows us to create an instance of a type without having to declare it explicitly in code.
How To Use Activator.CreateInstance?
To use Activator.CreateInstance
, we first need to specify the type we want to create an instance of. We can pass either the type name or a Type
object representing the type we want to instantiate. Additionally, if the type requires constructor arguments, we can pass them as parameters to CreateInstance
.
Let’s consider a simple example where we have a class named Person
with properties like Name
and Age
. We can dynamically create an instance of this class using Activator.CreateInstance
as follows:
Type personType = typeof(Person);
object personInstance = Activator.CreateInstance(personType);
In the above code snippet, we obtain the Type
object for the Person
class using the typeof
operator. Then, we pass this type to Activator.CreateInstance
, which returns an object instance of the Person
class.
Handling Constructor Arguments with Activator.CreateInstance
Often, classes require constructor arguments for their instantiation. We can handle this scenario by passing the required arguments to Activator.CreateInstance
. Let’s extend our previous example to include a parameterized constructor in the Person
class:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
Now, when creating an instance of Person
using Activator.CreateInstance
, we need to supply the necessary constructor arguments:
Type personType = typeof(Person);
object personInstance = Activator.CreateInstance(
personType,
"John Doe",
30);
In this case, we provide the arguments "John Doe"
and 30
to CreateInstance
, which will be used by the constructor of the Person
class to initialize the properties.
Quick Recap on Activator.CreateInstance in C
Activator.CreateInstance
is a helpful tool that we have access to when it comes to reflection in C#. We looked at a quick set of simple code examples that show us how to create objects and pass parameters in the constructors.
Reflection in C# is a powerful tool — but it’s easy to abuse. Activator.CreateInstance
opens up new possibilities for creating flexible and extensible code, allowing for dynamic object creation and manipulation. By leveraging reflection properly (i.e. without overdoing it at every possible opportunity) in your projects, you can build some really cool things. It allows you to create objects on the fly, based on runtime information, and opens up opportunities for more dynamic systems — like leveraging plugins!
If you found this useful and you’re looking for more learning opportunities, consider subscribing to my free weekly software engineering newsletter and check out my free videos on YouTube!
Want More Dev Leader Content?
- Follow along on this platform if you haven’t already!
- Subscribe to my free weekly software engineering and dotnet-focused newsletter. I include exclusive articles and early access to videos: SUBSCRIBE FOR FREE
- Looking for courses? Check out my offerings: VIEW COURSES
- E-Books & other resources: VIEW RESOURCES
- Watch hundreds of full-length videos on my YouTube channel: VISIT CHANNEL
- Visit my website for hundreds of articles on various software engineering topics (including code snippets): VISIT WEBSITE
- Check out the repository with many code examples from my articles and videos on GitHub: VIEW REPOSITORY
Top comments (4)
Have you tried some benchmark? Where do you think is proper usecase for activator?
I personally don't use reflection for things on a hot path of an application - just for plugin initialization mostly. As a result, I have not benchmarked this kind of code vs calling a constructor directly, but certainly through reflection I would expect a slowdown.
I'm not sure how bad it gets though, but it's never been in a situation where I've needed to worry :) For example, if you were using this kind of approach in a game and needed to use Activator.Instance to create objects, I'd suspect you'd want to look for another way (or run benchmarks to see truly how good/bad it is).
But yeah, "proper" case for me is really when you have no other choice when it comes to dynamically creating objects that you don't know type information about at compile time. Plugins are an excellent example :)
I have tried some simple benchmark and here are some results
I ended up creating a YouTube video to dive a bit deeper into this :)
youtu.be/Djq7eMI_L-4
Let me know if you find that helpful!