intantiate an object using a type

  • Thread starter Thread starter rapataa
  • Start date Start date
R

rapataa

hi,

anyone knows how to instantiate a class, using only the type?

for example:

public void Init(Type sssType)
{
object = new sssType ?????
}



the method Init will be called like this:

Sustem.Typ sss = typeof(myClass);
Init(sss);
 
public void Init(Type sssType)
{
object = System.Activator.CreateInstance(sssType);
}

(You don't actually need the "System." in there, but I wanted to show which
namepspace it was in).
 
Assuming that the class has a public default constructor:

imports System.Reflection;

public void Init(Type sssType) {
ConstructorInfo constructor = sssType.GetConstructor(new Type[]{});
if(constructor != null) {
object myObject = constructor.Invoke(new object[]{});
// Use myObject
}
}
 
Try this:

public void CreateInstance(type myType)
{
Assembly assembly = Assembly.GetCallingAssembly();
object typeObject = assembly.CreateInstance(myType.FullName);
}
 
Manohar Kamath said:
Try this:

public void CreateInstance(type myType)
{
Assembly assembly = Assembly.GetCallingAssembly();

But you don't neccesarily know that the type will be in the calling
assembly. It could be in mscorlib...
 
Back
Top