System.Type parameter

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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)
 
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
 
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)
 
Back
Top