Trying To Get The Name Of A Variable as a String VB.NET

ATD picture ATD · Jan 25, 2013 · Viewed 14.3k times · Source

I'm trying to return the name of a variable as a string.

So if the variable is var1, I want to return the string "var1".

Is there any way I can do this? I heard that Reflection might be in the right direction.

Edit:

I'm essentially trying to make implementation of an organized treeview simpler. I have a method that you give two strings: rootName and subNodeText. The rootName happens to be the name of a variable. The call to this method is from within a with block for this variable. I want the user to be able to call Method(.getVariableAsString, subNodeText) instead of Method("Variable", subNodeText). The reason for wanting to get it programmatically is so that this code can be simply copied and pasted. I don't want to have to tweak it every time the variable is named something abnormal.

Function aFunction()
   Dim variable as Object '<- This isn't always "variable".
   Dim someText as String = "Contents of the node"

   With variable '<- Isn't always "variable". Could be "var", "v", "nonsense", etc
      'I want to call this
      Method(.GetName, someText)
      'Not this
      Method("Variable",someText)

   End With
End Function

Answer

Edwin picture Edwin · Jan 25, 2013

This is now possible starting with VB.NET 14 (More information here):

Dim variable as Object
Console.Write(NameOf(variable)) ' prints "variable"

When your code is compiled, all the variable names you assign are changed. There is no way to get local variable names at runtime. You can, however, get names of the properties of a class by using System.Reflection.PropertyInfo

 Dim props() As System.Reflection.PropertyInfo = Me.GetType.GetProperties(BindingFlags.Public Or _
                                                                                     BindingFlags.Instance Or BindingFlags.DeclaredOnly)

 For Each p As System.Reflection.PropertyInfo In props
     Console.Write(p.name)
 Next