Creating (decimal?) instances through the Activator class

J

jmnobre

Good morning,

Does anyone knows why:

Activator.CreateInstance( typeof( decimal? ), new object[]
{ 10M } ).GetType().FullName

returns "System.Decimal" ??

Also,

Convert.ChangeType( Activator.CreateInstance( typeof( decimal? ), new
object[]{ 10M } ), typeof( decimal? ) )

gives an InvalidCastException saying that it cannot convert from
decimal to decimal?.

I do need to create Nullable<> instances base on runtime info... but I
just find out that this is not the way....

Any help would be appreciated.

Thanks in advance
jmn
 
K

Kornél Pál

Hi,

The whole idea of using Activator for creating a nullable type is
broken. Nullable types are special because null is boxed if their value
is null and the underlying type gets boxed when non-null.

Just use the following:
decimal? d1 = 10M;

Kornél

Peter said:
Good morning,

Does anyone knows why:

Activator.CreateInstance( typeof( decimal? ), new object[]
{ 10M } ).GetType().FullName

returns "System.Decimal" ??

Also,

Convert.ChangeType( Activator.CreateInstance( typeof( decimal? ), new
object[]{ 10M } ), typeof( decimal? ) )

gives an InvalidCastException saying that it cannot convert from
decimal to decimal?.

I do need to create Nullable<> instances base on runtime info... but I
just find out that this is not the way....

Nullable<T> is a generic type, so if I recall correctly you need to use
the specific methods meant for creating generic types (I haven't looked
it up, but I seem to recall that you can pass the generic type along
with the necessary type parameters).

MSDN is your friend. :)

Pete
 

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

Top