tags:

views:

46

answers:

1

I have code like this:

Type typPrecise = MostPrecise(typeof(int), typeof(double));//Evaluates to double

var varGeneric = typeof(Number<>);
var varSpecific = varGeneric.MakeGenericType(typPrecise);
dynamic nmNumber = Activator.CreateInstance(varSpecific);

The nmNumber is of dynamic type and essentially produces a Generic Number. How do I then specify the number of items in Number.

I basically want to accomplish this but by using the dynamic code above:

Number<typPrecise> whatever = new Number<typPrecise>(10);

An answer using 4.0 concepts is welcome.

+3  A: 

Call the overload of Activator.CreateInstance that accepts constructor arguments:

dynamic nmNumber = Activator.CreateInstance(varSpecific, new object[] { 10 });

Incidentally note that the List<T>(int) constructor sets the initial capacity of the List, not the initial number of items (Count). The initial Count is always 0.

itowlson
How did I *not* know about an overload of CreateInstance that includes arguments? Doh!
Jon Skeet
So the 10 in the object[] just specifies the number of items. It doesn't add an object[] with a single item of 10?
Chris
Just looked into the constructor doc. Very helpful thanks.
Chris
+1 for teaching something to Jon Skeet ;)
Thomas Levesque