How to write the most generic factory method in c#

+1 vote
asked Mar 29, 2016 in Programming by Andy Mount Student (280 points)

Hi,

I want to implement a static factory method in the base class of some arbitary class tree.

I should be able to call each constructor even if they have different arguments.

 

It should somehow look like the following prototype:

public static T CreateInstance<T>(List<object> args);

Thank you for your help.

1 Answer

0 votes
answered Mar 29, 2016 by Bugstacker Senior (4,800 points)

You could achieve that like this:

public static T CreateInstance<T>(params object[] args) where T : BaseType
{
    T instance = default(T);
    Type type = typeof(T);

    Type[] types = new Type[args.Length];

    for(int i = 0; i < args.Length; i++)
    {
        types[i] = args[i].GetType();
    }

    ConstructorInfo ctorInfo = type.GetConstructor(types);
    instance = ctorInfo.Invoke(args) as T;

    return instance;
}

 

  1. Pass the arguments using the params keyword
  2. Constrain the genric type to your base class
  3. Use reflection to construct your instance
Welcome to Bugstacker Q&A, where you can ask questions concerning Game Development, Programming and Design and receive answers from other members of the community.

Help for

...