Hobbyist
Hobbyist

Reputation: 16202

C# Creating an instance of a class from type

I'm trying to get this functionality:

Class<?> c = Class.forName(dir.substring(6).replaceAll("/", ".") 
                       + file.getName().replaceAll(".java", ""));
Packet packet = (Packet)c.newInstance();

For any of you who are familliar with it, the above code is Java, it gets the class from a directory and then creates an instance of it, which is what I'm trying to do in C#

I've gotten about this far, and now I'm stuck...

  foreach(Type t in assembly.GetTypes())
  {
        if (t.BaseType == typeof(Packet))
        {

Basically I need to find a way to construct a class from the Type, then create an instance of it.

I've tried using the Activator, like so:

foreach(Type t in assembly.GetTypes())
{
      if (t.BaseType == typeof(Packet))
      {
           string namespaceName = t.Namespace;
           string className = t.Name;
           var myObj = Activator.CreateInstance(namespaceName, className);

but I can't figure out how to reference it as a class instead of an ObjectHandle

Upvotes: 1

Views: 2974

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

It seems like you are looking for Activator.CreateInstance method

var instance = Activator.CreateInstance(type);

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1501646

Basically I need to find a way to construct a class from the Type, then create an instance of it.

A Type is a class (or a struct, etc). Once you've got an appropriate Type, there are various options for instantiating it... for example, Activator.CreateInstance(), or call Type.GetConstructors(), find the right constructor and then invoke it.

All of these approaches return object, so you'll need to cast:

Packet packet = (Packet) Activator.CreateInstance(type);

Upvotes: 7

Related Questions