2

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, the second one worked perfectly! Is it worth it storing the assembly info to use with the first or is it still fine practice to retrieve it using method #2?
@jokulmorder if you are sure it'll always be in that assembly, the second approach is fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.