"Dynamicly" create variables

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi!

I would like to dim variables using dynamic code, like following:

Dim type as String = "Integer"
Dim variable as [type]

(the issue is in fact about my own types,
but let us isolate the issue using the native types)

Best regards,
Benjamin
 
Dim variable As Integer ?? Generics (2.0), using "Object" (the type is not
supposed to be known at compile time ?), creating code using CodeDom ?

Explaining what you are trying to do may help...

In particular if doing simply :
Dim variable As Integer
You can use Variable.GetType to get the type as a type variable (ie. the
other way round, you can the type name from the variable instead of
creating the variable using the type name).

Patrice
 
Benjamin said:
I would like to dim variables using dynamic code, like following:

Dim type as String = "Integer"
Dim variable as [type]

(the issue is in fact about my own types,
but let us isolate the issue using the native types)

If you don't know the type at compile-time, what use do you expect to
get from declaring a variable of that type? You couldn't do anything
more with it (at least with Option Strict On) than you could with
Object.
 
Hello Benjamin,


I agree with Jon, if you don't know it's type, you won't be able to do much
with it.
But, I managed to do what you're asking for:



using System;
using System.Runtime.Remoting;

statc void Example()
{

int MyInt = 0;

string NameOfType = MyInt.GetType().FullName.ToString();
string NameOfAssembly = MyInt.GetType().Assembly.FullName.ToString();

ObjectHandle hnd = Activator.CreateInstance(NameOfAssembly, NameOfType);

int MyNewlyCreatedInt = (int) hnd.Unwrap();

}
 
Brian said:
I agree with Jon, if you don't know it's type, you won't be able to do much
with it.
But, I managed to do what you're asking for:

Not quite.
using System;
using System.Runtime.Remoting;

statc void Example()
{

int MyInt = 0;

string NameOfType = MyInt.GetType().FullName.ToString();
string NameOfAssembly = MyInt.GetType().Assembly.FullName.ToString();

ObjectHandle hnd = Activator.CreateInstance(NameOfAssembly, NameOfType);

int MyNewlyCreatedInt = (int) hnd.Unwrap();

}

That's creating a new instance (I'd just use the version which returned
an Object reference personally) but it's not creating a new *variable*
as requested. I suspect the OP doesn't really need to create a new
variable though - it's hard to say without more information.
 
Back
Top