System.Type parameter

G

Guest

I am passing a System.Type parameter into a method. I would like to create an object of that type from the System.Type.

for example

public CreateAnObject( System.Type objectType)
{
m_MemberObject = new "The class represented by objectType";
}

and called by

CreateAnObject(typeof(someClass));

Underlying reason is I want to pass a class in a custom attribute so I cannot pass an instantiated object (must be a class or a constant)

Thanks

Martin
 
N

Nicholas Paldino [.NET/C# MVP]

Martin,

You can pass the type to the static CreateInstance method on the
Activator class. This will allow you to create an instance based on the
type. However, you have to know if the type constructor takes parameters or
not, and if it does, you have to supply them.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Martin Montgomery said:
I am passing a System.Type parameter into a method. I would like to create
an object of that type from the System.Type.
for example

public CreateAnObject( System.Type objectType)
{
m_MemberObject = new "The class represented by objectType";
}

and called by

CreateAnObject(typeof(someClass));

Underlying reason is I want to pass a class in a custom attribute so I
cannot pass an instantiated object (must be a class or a constant)
 
S

Soren Staun Jorgensen

Martin Montgomery said:
I am passing a System.Type parameter into a method. I would like to create
an object of that type from the System.Type.
for example

public CreateAnObject( System.Type objectType)
{
m_MemberObject = new "The class represented by objectType";
}
[Snip]

Something like;
public void CreateAnObject( System.Type objectType)
{
object o = Activator.CreateInstance(objectType);
// do other stuff, and sure to put above into a try-catch statement
}

Soren
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi Martin,

Hi Martin,
In addition to the solution Nicholas and Soren gave you I would add that you
can use Type.GetConstructor to obtain the construcotr you want to use.
Having ConstructorInfo object you can call Invoke method to create an
instance of the type.
--

Stoitcho Goutsev (100) [C# MVP]


Martin Montgomery said:
I am passing a System.Type parameter into a method. I would like to create
an object of that type from the System.Type.
for example

public CreateAnObject( System.Type objectType)
{
m_MemberObject = new "The class represented by objectType";
}

and called by

CreateAnObject(typeof(someClass));

Underlying reason is I want to pass a class in a custom attribute so I
cannot pass an instantiated object (must be a class or a constant)
 

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