Dynamic type creation questions

  • Thread starter Thread starter ~~~ .NET Ed ~~~
  • Start date Start date
N

~~~ .NET Ed ~~~

Hi, I am confronted with a problem that is probably related to a part of the
..NET framework I am not familiar with, so here are the two "problems".

1. I have a value in string form, and a string indicating the actual system
type of the value:
string itemValue = "2500.6";
string itemType = "System.Decimal"

Having that information I want to dynamically be able to recreate the
item in its original type (ie. decimal item = 2500.6M").

I know I can obtain the type using the following:
System.Type itemNativeType = System.Type.GetType(itemType);

But then at this point I do not know how I could do something that would
be equivalent to decimal.Parse(itemValue) but then in a way that it can be
done in a generic way (for numeric types at least) using the itemNativeType
variable shown above. Basically I want to avoid having a large switch
statement (or if chain) for each of the supported data types, ie this is not
what I want:

if (itemType.Equals("System.Decimal"))
decimal d = decimal.Parse(itemValue);
if .....


2. Then the 2nd problem that occupies my mind is how to dynamically create a
new type. Say I want to dynamically create a structure whose type I would
name SAnyType and to which I could dynamically ADD members of any of the
basic .net types (int, string, float, decimal, etc.). So the structure may
contain two members (int, float) in one instance and then under other
circumstances just one (of any type) or more of any combination thereof. Is
that possible? I have been trying to find any sample on the internet without
any luck.

Thx,
Emil
 
The saga continues.... Question #2 is still 100% open. As for question #1 I
found a way but am still halfways:

1. I can use the method below to get a System.Type based on the string name
of the type (itemType). Then I used
some obscure things from System.Reflection to get access to the type's
Parse method if it exists. Since I am
dealing with numeric & boolean & string types this handling is ok, if
parse is found it can be used, but I haven't
gotten there yet, because....

1a) I obtained my type (System.Type) as itemNativeType below. This can be
almost any of the types mentioned
above (int, byte, long, etc.). The question that I have now is, HOW,
based on itemNativeType (ie. it may be
ANY of those types) can I create an instance of that type. For example,
to create an instance of a long, or
boolean or string?

The problem i see here is that some of those types (int for example)
are value types so I cannot get a handle
to the type's constructor or initializer. Any ideas?
 
Back
Top