jokul
jokul

Reputation: 1339

Create object of type determined at runtime with non-default constructor

i have an abstract class A and implementations B and C. I also have a database that stores information on A objects. This table has a column called "Name" that will be used to determine whether B or C should be constructed using the data.

public abstract class A { }

public class B,C : A
{
    public B,C(TableData data)
    {
        //Do Stuff.
    }
}

public class TableData
{
    string Name { get; set; }
}

Now, if Name is "Banana" I want this to create an instance of B; if it is "Carrot" I want this to create an instance of C:

A myObj = { Reflection? }

Where Reflection somehow uses the B or C constructor and assigns this newly created object to myObj. I have looked into using reflection, but most of the methods there that allow use of the non-default constructor are very complicated and take parameters I have never worked with before:

http://msdn.microsoft.com/en-us/library/System.Activator.CreateInstance(v=vs.110).aspx http://msdn.microsoft.com/en-us/library/dd384354.aspx

Is there a better way to do this? If not, how do I use the second link to dynamically assign this type?

If there is some way to simply do this:

CreateInstance("Namespace.Type", [ ConstructorParam1, ConstructorParam2, ... ])

That is all I need.

Upvotes: 2

Views: 269

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064134

If you are expecting there to be a parameter that takes a TableData, then this is simply:

Type type = Type.GetType(qualifiedName);
TableData tableData = ...
A obj = (A)Activator.CreateInstance(type, tableData);

Noting that the qualifiedName should include the assembly information; if it doesn't, you'll want to resolve that first - perhaps:

Type type = typeof(A).Assembly.GetType(fullName);

where B / C etc is in the same assembly as A, and where fullName is "Namespace.B" or similar.

Upvotes: 5

Related Questions