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
A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $. The $ is part of the name.
To check if a variable contains a value that is a string, use the isinstance built-in function. The isinstance function takes two arguments. The first is your variable. The second is the type you want to check for.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With