Search code examples
.netvb.netoop.net-2.0system.reflection

Create a variable of an instance object of a class at runtime in VB.NET


I am trying to create new variables inside a class after creating its object at runtime. The problem is that I don't know the variable names or the value beforehand so I have to create the new variables at runtime.

For e.g. -

Public Class Test
    Public Sub Test()
    End Sub
    Public Function Fval(ByVal Field As Object) As Object
        Return Field(1)
    End Function
End Class

''Creating the object of Test class
Public Class ExecTest
    Public Sub Main(ByVal args() As String) 
        Dim obj as New Test()
        Dim des As ScriptControlClass = New ScriptControlClass()
        des.Language = "VBScript"
        des.AddObject("TS", obj, True)
        Dim xx as Object = des.Eval("Fval(ABC)")
    End Sub
End Class

Edit: This is a more elaborate explanation of my code. If you observe that in the Eval function I have tried to evaluate Fval(abc). Now the object array abc is not declared in the Test class because it existence is not known beforehand. What I want to do is create an object array abc of length 2 and populate it with some values and when Fval(abc) is called then then the value of index 1 should be the return value of Eval function.


Solution

  • You can not add anything to a type in .NET after the type is created. A type is really fixed.
    You can create create a new type at runtime that inherits from Test, but that will be a lot of work both to create and to access the members of that type.

    A much more useful approach is to create a Dictionary(Of T, V) in the Test class and store the values in that dictionary with the name of the variable as the key in the dictionary.