Trying to get a variable name as a VB.NET string

I am trying to return the variable name as a string.

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

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

Edit:

I try to make the implementation of organized treeview simpler. I have a method that you give to two lines: rootName and subNodeText. The name rootName is the name of the variable. This method is called internally with a block for this variable. I want the user to be able to call the method (.getVariableAsString, subNodeText) instead of the method ("Variable", subNodeText). The reason that he wants to get it programmatically is because this code can simply be copied and pasted. I do not want to configure it every time a variable is called 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 
+6
source share
2 answers

Now it is 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 that you assign change. Unable to get local variable names at run time. However, you can get class property names 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 
+9
source

There is no way to do this, and it doesn't even make any sense (if you want a variable name, just ... enter it?).

-1
source

All Articles