Constructing ValueTypes via Reflection

  • Thread starter Thread starter dmcdougald
  • Start date Start date
D

dmcdougald

I have scenario where I need to create an object of an unknown type.
Reference types work fine. I call Type.GetConstructors(), let the
user pick a ConstructorInfo and then call ConstructorInfo.Invoke().

However, for the value types I have tested (like Int32)
GetConstructors doesn't return anything.

Any help is appreciated.
 
I have scenario where I need to create an object of an unknown type.
Reference types work fine. I call Type.GetConstructors(), let the
user pick a ConstructorInfo and then call ConstructorInfo.Invoke().

However, for the value types I have tested (like Int32)
GetConstructors doesn't return anything.

Use Activator.CreateInstance to create a value, not passing in any
constructor parameters. Although at the CLR level value types don't
have parameterless constructors, Activator.CreateInstance treats them
as if they do. (At the C# level they do, according to the spec. It's a
bit confusing in terminology terms, to be honest - but the behaviour is
simple.)

Here's an example:

using System;

class Test
{
static void Main()
{
int i = (int) Activator.CreateInstance(typeof(int));
Console.WriteLine (i);
}
}
 

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

Back
Top