4

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?

1
  • I doubt this would compile Commented Oct 1, 2013 at 7:47

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Can I create a Type object of a certain type? You mean something like Dim authorType As System.Type = GetType(Author)? and then create objects, lists Yes, look at my answer. * or cast objects to this type from this Type object* That doesn't make sense, since casting is only useful at compile-time. You don't know which type the System.Type you like to cast to will actually represent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.