Consider following code:
Dim S1 As String = "a"
'this is the string in a file
Dim StringFromFile As String = "S1=hello"
Dim temp() As String = Split(StringFromFile, "=", -1, CompareMethod.Binary)
'temp(0) = variable name
'temp(1) = variable value
'my question is: how to assign value to S1?
I have declared a string named S1. Now I want to assign new value to S1. The new string value is stored in a file using following format: [variable name][= as separator][string value]. How do I assign the value to S1 after retrieving the string variable name and value that stored in a file?
NOTE:
temp(0) = "S1"
temp(1) = "hello"
It should be noted that the string with the data comes from a file that may change from time to time! When the file changes, I want the variables to change as well.
Further clarification
I need a piece of code that when processing a string like this "S1=hello", the code will first find a declared variable (i.e. S1), and then assign the S1 variable with "hello" string. The "=" just acted as separator for variable name and variable value.
UPDATE:
My attempt to use Mathias Lykkegaard Lorenzen's EDIT 2 example but failed with "NullReferenceException" on this line "Field.SetValue(Me, VariableValue)"
. Please help me fix the problem. Following is my code based on Mathias Lykkegaard Lorenzen's EDIT 2 example:
Public Sub Ask()
Try
Dim S1 As String = "a"
Dim StringFromFile As String = "S1=hello"
Dim temp() As String = Split(StringFromFile, "=", -1, CompareMethod.Binary)
'temp(0) = variable name
'temp(1) = variable value
'my question is: how to assign value to S1?
Dim TypeOfMe As Type = Me.GetType()
'did this for readability.
Dim VariableName As String = temp(0)
Dim VariableValue As String = temp(1)
'get the field in the class which is private, given the specific name (VariableName).
Dim Field As FieldInfo = TypeOfMe.GetField(VariableName, BindingFlags.NonPublic Or BindingFlags.Instance)
'set the value of that field, on the object "Me".
Field.SetValue(Me, VariableValue) '<-- this line caused NullReferenceException
MessageBox.Show(S1)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub