Creating (decimal?) instances through the Activator class

  • Thread starter Thread starter jmnobre
  • Start date Start date
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
 
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
 
Back
Top