Reflection

  • Thread starter Thread starter narcisiss
  • Start date Start date
N

narcisiss

Hi,
does it exist a method to get the type of a variable, given its name?

e.g.
int a = 0;
t = ???.GetTypeByName("a");

Thank you,
Federico
 
Hello Federico,

You can use Type.GetType but you will have to specify the full namespace of
the class including its name and its assembly name.

For example:

Type t = Type.GetType("MyNamespace.MyNamespace2.MyClass, MyAssemblyName")

The problem with this options is that if the assembly for this type is not
loaded and is only available in the GAC you will have to specify the full
strong name of the assembly.
 
narcisiss said:
does it exist a method to get the type of a variable, given its name?

e.g.
int a = 0;
t = ???.GetTypeByName("a");

Not for a local variable, no. If you've got an instance/static
variable, you can get that from the enclosing type using GetField, and
then use FieldInfo.FieldType to get the type of the variable.
 
narcisiss said:
Thank you, i was looking for this kind of feature.. but i've to solve the
problem in another way :)

If you're after local variables though, you know the type because
you've just declared them - so just use:

Type t = typeof(int);
 
Back
Top