Calling constructor from a System.Type?

D

Daisy

What I want to do is this:

Object1[] list = (Object1[])this.MyMethod(typeOf(Object1), "Object1",
"string1", "string2");
and
Object2[] list = (Object2[])this.MyMethod(typeOf(Object2), "Object2",
"string1");


But I can't find how to call a constructor from a type


// Do I have to return object[]?
public object[] MyMethod(Type t, string name, params object[] spParams)
{
DataReader dr = Data.Get(name, spParams);

retVal = new t.Construct(dr); // <-- THIS LINE NEEDS TO CALL CONSTRUCTOR

return (object[])retVal;

}


I've tried msdn, but can't find what I'm looking for
 
M

Mattias Sjögren

If you want to create an instance of the type t (and at the same time
call one of its constructors), the easiest way is to use
Activator.CreateInstance().



Mattias
 
P

Philip Rieck

Try using
Object retVal = Activator.CreateInstance( t, new object[] { /*params to
constructor go here */ dr });

Or you can use the .Invoke method on the type object you have... check the
bindingflags to call the constructor
 
J

Jon Skeet [C# MVP]

But I can't find how to call a constructor from a type

As well as Activator.CreateInstance, you could also call GetConstructor
on the Type, and then Invoke on the Constructor.
 

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