Question

I am using (a slightly extended version of) the following code in a factory-pattern style function:

public class SingleItemNew : CheckoutContext { public BookingContext Data { get; set; } public SingleItemNew(BookingContext data) { Data = data; } } public CheckoutContext findContext(BookingContext data) { Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString()); CheckoutContext output = Activator.CreateInstance(contextType, BindingFlags.CreateInstance, new[] { data }) as CheckoutContext; return output; }

however, it throws a constuctor not found exception when run, and I cannot figure out why.

The data.Case.ToString() method returns the name of a class, SingleItemNew, that has a constructor taking a single argument.

Does anyone have any idea what the problem is?

Cheers, Ed

Was it helpful?

Solution

Try this one:

  Type contextType = Type.GetType("CheckoutProcesses." + data.Case.ToString());
  CheckoutContext output = 
      (CheckoutContext)Activator.CreateInstance(contextType, data);

The reason you code doesn't work is that Activator.CreateInstance doesn't really have the overload you want. So you might wonder why the code compiles at all! The reason is, it has an overload that takes (Type type, params object[] args) which matches your method call so it compiles but at runtime, it searches your type for a constructor taking a BindingFlags and a BookingContext[] which is clearly not what your type has.

OTHER TIPS

Is the constructor public?

Is the single parameter of type BookingContext?

The trouble is, this is clearly part of a bigger system - it would be much easier to help you if you could produce a short but complete program which demonstrated the problem. Then we could fix the problem in that program, and you could port your fix back to your real system. Otherwisewise we're really just guessing :(

Does the SingleItemNew constructor take BookingContext as parameter? If it does not match exatcly it will fail:

class ParamType   {    }
class DerivedParamType : ParamType    {    }
class TypeToCreate
{
    public TypeToCreate(DerivedParamType data)
    {
        // do something
    }
}

ParamType args = new ParamType();
// this call will fail: "constructor not found"
object obj = Activator.CreateInstance(typeof(TypeToCreate), new object[] { args });

// this call would work, since the input type matches the constructor
DerivedParamType args = new DerivedParamType();
object obj = Activator.CreateInstance(typeof(TypeToCreate), new object[] { args });

This worked for me.

Type.GetType("namespace.class, namespace");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top