1

I am working in .Net 3.5, looking at all the various constructors for Activator.CreateInstance. I want to create an instance of a class, calling a particular constructor. I do not have the class type, only its name. I have the following, which works, but actually winds up calling the parameterless constructor first, then the one I want. This is not a terribly big deal, but the parameterless constructor calls a rather busy base constructor, and the constructor I want to call does, too.

In other words, given a type, calling CreateInstance with parameters is easy (only the last two lines below), but given only a type name, is there a better way than this?

ObjectHandle oh = Activator.CreateInstance( "MyDllName", "MyNS." + "MyClassName" );
object o = oh.Unwrap( );
object newObj = Activator.CreateInstance( o.GetType( ), new object[] { param1 } );
return ( IMyDesiredObject )newObject;

Thanks!

2 Answers 2

1

You can use this overload of CreateInstance. It allows you to specify the type by name (string), as well as constructor arguments (6th parameter).

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

1 Comment

Thank you, Reed -- I saw that guy, but I didn't know what to do with the ActivationAttributes and SecurityInfo. The docs didn't indicate (as with Binder and Culture) that they could be null, but it turns out that they can. Works for me!
0

The way I was able to get this to work was

  Type type = BuildManager.GetType(ServiceRef + ".SDK",false);

  Object nl = Activator.CreateInstance(type);

The BuildManager.GetType requires the fully qualified classname, in your case this is where you would pass "MyNS." + "MyClassName"

1 Comment

What is BuildManager? It must be from some library you use cause its not in .NET

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.