How to initate a new object when...

  • Thread starter Thread starter Cepheus
  • Start date Start date
C

Cepheus

Hi,
I want to initate a new object. The Type of the object is only known during
runtime and saved in a variable as System.Type. How do I create and initiate
that object?
Thanks, Rainer.
 
Cepheus said:
I want to initate a new object. The Type of the object is only known during
runtime and saved in a variable as System.Type. How do I create and initiate
that object?

Have a look at Activator.CreateInstance.
 
Hi,
Thanks for your response. My problem is, that this does not work for simple
types (e.g.: int, string, ...).
Rainer.
 
Cepheus said:
Thanks for your response. My problem is, that this does not work for simple
types (e.g.: int, string, ...).

Um, I believe it does. For example:

using System;

class Test
{
static void Main()
{
char[] chars = {'h', 'e', 'l', 'l', 'o'};
object[] parameters = {chars};

string x = (string) Activator.CreateInstance
(typeof(string), parameters);

Console.WriteLine (x);
}
}

Of course, there has to be an appropriate constructor defined, but when
there is, it's fine.
 
You are right. My fault. Thanks.

Jon Skeet said:
Cepheus said:
Thanks for your response. My problem is, that this does not work for simple
types (e.g.: int, string, ...).

Um, I believe it does. For example:

using System;

class Test
{
static void Main()
{
char[] chars = {'h', 'e', 'l', 'l', 'o'};
object[] parameters = {chars};

string x = (string) Activator.CreateInstance
(typeof(string), parameters);

Console.WriteLine (x);
}
}

Of course, there has to be an appropriate constructor defined, but when
there is, it's fine.
 
Back
Top