reflection: problem creating new instance

B

bowser

Hello, I have a problem with reflection. I posted it already a month
ago, but I had no luck with the answers...

Having two variables:
Type t;
string id;

initialized for example as t="Foo" and id="foo"

I need to make the equivalent of :
Foo foo = new Foo();

meaning, something like:
t id = new t();

(but obviously this is incorrect since id is a string and t is a
variable and can't be used for this purpose in this way).
I know how to instantiate the new object:
ConstructorInfo ci = t.GetConstructor(new Type[] { });
object obj = ci.Invoke(null);

But I need to assign name and type to it.
How can I do?

Thank you.

Alesssandro
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi


I don;t quite understand your post, but I think that you want to create an
instance of a class that you only know by name. If this is the case there
are a few way that you can do so.

If you know the assembly (and have a reference to it) where the class is
defined you can use Assembly.CreateInstance( string type)

There are other classes that are capable to create instances (AppDomain,
etc) take a look at CreateInstance method in MSDN and it will list all those
classes

Also note that you need to use the full name of the type, instead of "Foo"
you need to use "MyAssembly.Foo"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top