none
System.Reflection.FieldInfo.SetValue(obj, val) RRS feed

  • Question

  • I want to be able to set the fields of an object using the names of the fields.  If I knew all the names (e.g. "name" and "location") then I could use the following code:

        Public Sub SetFieldValue(ByRef obj As Object, ByVal FieldName As String, ByRef val As Object)
            Select Case FieldName 
                Case "name"
                    obj.name = val
                Case "location"
                    obj.location = val
        End Sub

    But I want this to be generally useful, so I tried the following:

        Public Sub SetFieldValue(ByRef obj As Object, ByVal FieldName As String, ByRef val As Object)
            Dim objType As Type = obj.GetType()
            Dim pInfo As System.Reflection.FieldInfo = objType.GetField(FieldName)
            pInfo.SetValue(obj, val)
        End Sub  

    It runs, throws no errors, but does not change obj's fields.  I note on other threads that this approach does not work for Structure Fields (as shown here), only Class Properties.  Neither Fields nor Properties are working for me.  Is there another way to do this?

    Thanks

    Mike

    Tuesday, January 15, 2013 7:17 AM

Answers

  • You don't have to use the ByRef. What kind of an objects, class or structure, are those where you are setting value?

    Below code should be working fine.

    Imports System.Reflection
    
    Module Module1
    
        Sub Main()
            Dim str As New Store()
            str.name = "Test"
            Console.WriteLine(str.name)
            SetFieldValue(str, "name", "Changed name")
            Console.WriteLine(str.name)
            Console.ReadKey()
        End Sub
    
        Sub SetFieldValue(ByVal obj As Object, ByVal fieldName As String, ByVal value As Object)
            Dim type As Type = obj.GetType()
            Dim fld As FieldInfo = type.GetField(fieldName)
            If fld IsNot Nothing Then
                fld.SetValue(obj, value)
            End If
        End Sub
    
    End Module
    
    Public Class Store
        Public name As String
        Public location As String
    End Class

    Tuesday, January 15, 2013 9:49 AM