How can I reference a .NET type when it is passed in as a string?

55 Views Asked by At

I have a dll with an API provided by a vendor. They use a "type" to give mnemonic values to an integer;

ele.dog = 1
ele.cat = 2
etc.

I can from within the module reference ele.dog when I need a 1, 2 for cat, etc.

dim myEle As TheirClass.ele = ele.dog

However I would like to be able to translate a string variable from "dog" to "1". What is the syntax to do this?

The reason is, I need to pass back to their class the "1" and all I have is dog.

2

There are 2 best solutions below

0
Andy On

You can call Type.GetType() (or possibly Assembly.GetType(), using the vendor's assembly) to get an instance of Type from the fully qualified typename. From there, you can use the various reflection APIs to create an instance of that type (such as Type.GetConstructor()).

Once you have an instance of that class, you can cast the object to the actual type that you know it is and use it as you normally would.

0
Paul Stearns On

Thanks to comments by #DStanley, I looked up parsing. The equivalent to;

dim myEle As TheirClass.ele = ele.dog

is

myVar = "dog"
dim myEle as TheirClass.ele = [Enum].Parse(GetType(TheirClass.ele), myVar)

At least this syntax doesn't give any errors.

It also has the added benefit of doing what I need as well.