PC Review


Reply
Thread Tools Rate Thread

Constructing ValueTypes via Reflection

 
 
dmcdougald@openspan.com
Guest
Posts: n/a
 
      26th Apr 2007
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.

 
Reply With Quote
 
 
 
 
Jon Skeet [C# MVP]
Guest
Posts: n/a
 
      26th Apr 2007
<(E-Mail Removed)> wrote:
> 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);
}
}

--
Jon Skeet - <(E-Mail Removed)>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
 
Reply With Quote
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Constructing a date NevilleT Microsoft Access VBA Modules 0 27th May 2009 06:59 AM
About xml constructing Reports to PDF files Microsoft Excel Programming 1 5th Jan 2008 05:17 PM
Reflection: Executing event code via reflection Shawn Hogan Microsoft VB .NET 0 13th May 2004 06:54 PM
Reflection: Executing event code via reflection Shawn Hogan Microsoft Dot NET Framework 0 12th May 2004 05:58 PM
Reflection Help: Copying data between objects using reflection Joe Bloggs Microsoft C# .NET 2 25th Mar 2004 09:58 AM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 10:47 AM.