VB.NET - reflection - Asked By Alex Kourkoumelis on 26-Oct-04 03:42 PM

I am trying to dynamically assign values to properties using reflection.  It works fine unless a property is defined as an enum.  When I try to conevrt the value to the expected type...I get a casting error... Here is the code... Any thoughts?  A better way perhaps?
Imports System.Reflection
Module Module2
    Sub Main()
        Dim class1 As Class1 = New Class1
        Console.WriteLine(class1.test1)
        SetProperty(class1, "test1", "testing")
        Console.WriteLine(class1.test1)
        Console.WriteLine(class1.test2)
        SetProperty(class1, "test2", "1")
        Console.WriteLine(class1.test2)
        Console.ReadLine()
    End Sub
End Module
Public Class Class1
    Private _test1 As String = "test"
    Public Property test1() As String
        Get
            Return _test1
        End Get
        Set(ByVal Value As String)
            _test1 = Value
        End Set
    End Property
    Private _test2 As TestEnum = TestEnum.Test0
    Public Property test2() As TestEnum
        Get
            Return _test2
        End Get
        Set(ByVal Value As TestEnum)
            _test2 = Value
        End Set
    End Property
    Public Enum TestEnum As Integer
        Test0 = 0
        Test1 = 1
    End Enum
    Function SetProperty(ByVal obj As Object, ByVal propertyName As String, _
        ByVal val As Object) As Boolean
        Dim pi As System.Reflection.PropertyInfo = obj.GetType().GetProperty(propertyName)
        Try
            ' get a reference to the PropertyInfo, exit if no property with that 
            ' name
            If pi Is Nothing Then
                Return False
            End If
            ' convert the value to the expected type
            val = Convert.ChangeType(val, pi.PropertyType)
            ' attempt the assignment
            pi.SetValue(obj, val, Nothing)
            Return True
        Catch
            Return False
        End Try
    End Function
End Class

Reflection is pretty slow - Asked By Robbe Morris on 26-Oct-04 09:38 PM

Why exactly are you doing this?
I did something like this for dynamically populating class properties from a DataTable utilizing custom attributes:
http://www.eggheadcafe.com/articles/20040221.asp
As for your enum, you might need to convert the string to an int first before converting it to the enum.  Just a guess.

Populating properties dynamically - Asked By Alex Kourkoumelis on 27-Oct-04 10:34 AM

The reason why I'm using reflection is because I need to populate the properties of a class at runtime with data passed in... in the form of XML.  I wasn't aware of any other way to populate properties dynamically.

Enums on reflection - Roni SH replied to Alex Kourkoumelis on 21-Jan-08 11:51 AM

If the value passed is an integer I think it should pass conversion, strings though need to be parsed by the enum type. Try implementing parsing instead of the convertion, maybe in an enum case only.