0

Let's supose we have constants like this:

Public Const fooBar = "whatever"
Public Const barBar = "else"

Than, elswhere in a Sub retrieve the constant value like this:

Function GetString(index1 as String, index2 as String) as String

    Dim index as String = index1 & index2
    Return ' ... here I need the magic to retrieve the specific constant resulted from the combination of those two indexes ...

End Function

Using Select Case statement is not an option, since there are a large number of contstants and posible combinations of them. Also, any other aproach is more than wellcome.

Sorin GFS
  • 477
  • 3
  • 18
  • Its not quite clear what you are trying to achieve. What relation does index have to the constants? – apc Sep 15 '17 at 10:44
  • @apc - there is no relationship between them, they are just arbitrary strings, supose `index1 = "foo"` , `index2 = "Bar"` and toghether are `fooBar` which is like the constant name `fooBar` – Sorin GFS Sep 15 '17 at 10:47
  • Take a look at this post (it's C# but you should be able to convert) https://stackoverflow.com/a/10261848/1856451 this will get you a list of constants which you can then search for the name. – apc Sep 15 '17 at 10:51
  • Then use FieldInfo.GetValue – apc Sep 15 '17 at 10:55
  • @apc - is not my case, and that solution is far more complicated for such a simple thing, in my situation I already know the constant names and I just look for a way to combine two strings to result their names and then to obtain the value of that specific constant name. – Sorin GFS Sep 15 '17 at 10:59

1 Answers1

0

Based on the answer here and extended: https://stackoverflow.com/a/10261848/1856451

Private Function GetConstantValue(type As Type, name As String) As String
    Dim fieldInfos As FieldInfo() = type.GetFields(BindingFlags.[Public] Or BindingFlags.[Static] Or BindingFlags.FlattenHierarchy)

    Dim field = fieldInfos.FirstOrDefault(Function(fi) fi.IsLiteral AndAlso Not fi.IsInitOnly AndAlso fi.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))

    If field IsNot Nothing Then
        Return field.GetValue(Me).ToString()
    Else
        Return "" 'Or throw an exception or something
    End If

End Function
apc
  • 5,306
  • 1
  • 17
  • 26
  • yes, this is the answer, it works! Thank you. `Return field.GetValue(Me)` should be converted to string, but I get it, thanks. – Sorin GFS Sep 15 '17 at 11:08