Search code examples
vb.netconstantsdynamic-programminggeneric-collections

VB.NET: Get dynamically value of constants


If have got the following definitions of constants:

Protected Const Xsl As String = "Configuration.Xsl"
Protected Const Form As String = "Settings.Form"
Protected Const Ascx As String = "Implementation.Ascx"
...

To fill a dictionary I use this constants as keys:

MyDictionary.Add(Converter.Xsl, "Item 1")
MyDictionary.Add(Converter.Form, "Item 2")
MyDictionary.Add(Converter.Ascx, "Item 3")
...

Now I run throug a loop of XML files and extract the name of the root node:

Dim document As New XmlDocument
document.Load(File.FullName)

Dim rootName As String = document.DocumentElement.Name

The root name matchs with the name of the constant. To get the value of an item from the dictionary I can use something like this:

Select Case rootName.ToUpper
    Case "Xsl".ToUpper
        DictionaryValue = MyDictionary(Class.Xsl)
    Case "Form".ToUpper
        DictionaryValue = MyDictionary(Class.Form)
    Case "Ascx".ToUpper
        DictionaryValue = MyDictionary(Class.Ascx)
    ...
    Case Else
End Select

If a constant is added or removed I also have to change the selection. Is there another way to get the value of a constant? Something like

DictionaryValue = MyDictionary(SomeFunctionToGetConstantValue(rootName))

Thanks for any response.


Solution

  • @Clara Onager

    My solution I used was the following

    Me.GetType.GetField(
        "Xsl",
        Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or System.Reflection.BindingFlags.FlattenHierarchy
    ).GetValue(Nothing)