Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign value to string using VB.NET?

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
like image 450
Pan Pizza Avatar asked Apr 29 '12 11:04

Pan Pizza


People also ask

How do you assign a value to a string variable?

String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.

How is string values handled in Visual Basic?

Once you assign a string to a String variable, that string is immutable, which means you cannot change its length or contents. When you alter a string in any way, Visual Basic creates a new string and abandons the previous one. The String variable then points to the new string.

What is string variable?

String variables -- which are also called alphanumeric variables or character variables -- have values that are treated as text. This means that the values of string variables may include numbers, letters, or symbols. In the Data View window, missing string values will appear as blank cells.


2 Answers

You can use reflection to set S1 value:

Imports System.Reflection

Public Class Form1
    Public S1 As String = "a"

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim StringFromFile As String = "S1=hello"

        Dim temp() As String = Split(StringFromFile, "=", -1, CompareMethod.Binary)
        'temp(0) = variable name
        'temp(1) = variable value

        SetS1(Me, "S1", temp(1))
        MessageBox.Show(S1)
    End Sub

    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="obj">the class that stores your S1 public field</param>
    ''' <param name="fieldName">that is your S1 field</param>
    ''' <param name="Value">S1 new value, that is hello</param>
    ''' <remarks></remarks>
    Public Sub SetS1(ByVal obj As Object, ByVal fieldName As String, ByVal Value As Object)
        Try
            Dim fi As FieldInfo = obj.GetType().GetField(fieldName, BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.NonPublic)
            If Not fi Is Nothing Then
                fi.SetValue(obj, Value)
            End If

        Catch ex As Exception

        End Try
    End Sub
End Class

Additional resource

There is a book about reflection which is very good, take a look:

Visual Basic .NET Reflection Handbook

Reflection is a mechanism provided by .NET that enables developers to make their programs more flexible and dynamic. Reflection makes it possible for applications to be more modular, extensible, and configurable. Building on the basics of object-orientation and the .NET type system, reflection provides mechanisms for dynamically examining, modifying, and even creating objects at run time. .NET also adds the ability for programmers to add attributes to their types, which provide metadata about the type which can be examined and used through reflection at runtime.

This book examines all the ways reflection can be used, and identifies practical applications and important programming techniques that rely upon reflection for their functionality. It covers the reflection API, the use of attributes in .NET, and also looks at the mechanisms .NET provides for dynamic generation of code - all techniques that allow developers to build more flexible, dynamic applications.

like image 116
Teen Avatar answered Oct 18 '22 10:10

Teen


If I understood your question correctly, you want to assign the value of temp(1) to the local variable with the same name as the value of temp(0). So, if your file contains S1=hello, S2=world, you want your code to assign "hello" to variable S1 (and "world" to variable S2, if such a variable exists).

Unfortunately, Visual Basic does not support assigning values to local variables whose names are determined at run-time. If S1 were a class field or property, you could assign it using reflection or a serialization library (e.g. XmlSerializer, which however expects input files to be in XML format rather than name=value pairs).

In general, a bit more context would be needed to suggest the best alternative for your situation. For example, if you just have names S1, ..., S20, I'd use an array. If your keys are arbitrary names, a Dictionary might be more appropriate.

like image 40
Heinzi Avatar answered Oct 18 '22 10:10

Heinzi