Is there any way to pass a type as a parameter?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'd like to create a method that will instantiate an object of whatever type
is specified as the argument. Is this possible?
This C# code does not work but it shows what I'm trying accomplish. Thanks.
private void NewObject(Type x)
{
x newObject = new x();
}
 
jacobryce said:
I'd like to create a method that will instantiate an object of whatever
type
is specified as the argument. Is this possible?
This C# code does not work but it shows what I'm trying accomplish.
Thanks.
private void NewObject(Type x)
{
x newObject = new x();
}

That's pretty close. Just use the System.Activator class to instanciate your
type, instead of the "new" operator.

.... you won't really be able to use strong typing though for your code. To
do this you'll need (want) an Interface definition or Abstract base class
you can use, and bring polymorphism into play...
 
Thank you. I've attempted to use System.Activator.CreateInstance(x) but it
errors that the parameter in the caller "is a 'type' but is used like a
'variable'." Any idea how to get around this?
 
jacobryce said:
Thank you. I've attempted to use System.Activator.CreateInstance(x) but it
errors that the parameter in the caller "is a 'type' but is used like a
'variable'." Any idea how to get around this?

Well, you could declare your variable as "object". That would involve
boxing if it's a value type, but that'll happen anyway because
CreateInstance's return type is object.
 
I did declare my instance variable as type Object, if I'm understanding you
correctly. The problem I had was in trying to pass in a Type as a parameter
in the method call:
private void NewObject(Type x)
{
x newObject = new x();
}

NewObject(anyType);
 
jacobryce said:
I did declare my instance variable as type Object, if I'm understanding you
correctly.

I think we're still miscommunicating.

Here's a code sample:

Given the Classes defined this way:
public interface MyInterface
{
string DoSomething(string a, string b);
}

public class ClassOne : MyInterface
{
public string DoSomething(string a, string b)
{
return a + b;
}
}
public class ClassTwo : MyInterface
{
public string DoSomething(string a, string b)
{
return "Hello " + a + "Goodbye " + b;
}
}

I can run the following Code:
private void button1_Click(object sender, EventArgs e)
{
Create(typeof(ClassOne));
}
void Create(Type t)
{
MyInterface i = System.Activator.CreateInstance(t) as MyInterface;
string s = i.DoSomething("test", "test");
}

Hope this helps.
 
Back
Top