vb.nettypescreateobject

Create an object from another objects type


In Visual Basic.net, can I create an Object, or a List of T with the type from another object.

Here is some code:

Dim TestObjectType As Author
Dim TestObject As TestObjectType.GetType

I am getting an error:

TestObjectType.GetType is not defined

EDIT

Can I create a Type object of a certain type, and then create objects, lists or cast objects to this type from this Type object?


Solution

  • Dim TestObject As TestObjectType.GetType will look for a type named GetType in the namespace TestObjectType.


    To create an instance of a class using System.Type, you can use Activator.CreateInstance:

    Dim TestObject = Activator.CreateInstance(TestObjectType.GetType())
    

    To create a generic list, you can use Type.MakeGenericType:

    Dim listType = GetType(List(Of )).MakeGenericType(TestObjectType.GetType())
    Dim list = Activator.CreateInstance(listType)
    

    Note that both snippets above return an Object; however, you can make use of generics to achieve compile time safety:

    Dim TestObject = CreateNew(TestObjectType)
    Dim AuthorList = CreateNewList(TestObjectType)
    
    ...
    
    Function CreateNew(Of T As New)(obj As T) As T 
        Return New T()
    End Function
    
    Function CreateNewList(Of T)(obj As T) As List(Of T)
        Return New List(Of T)
    End Function