Tim Hastings - NonHostile (because there's no need)

Weblog and collection of geeky articles.

  Home :: Who? :: Contact :: Links :: Subscribe subscribe
Christmas Shopping in LeedsAutumn 2007Visiting our new nephew Daniel


There are circumstances where we want to create an instance of an object using its name at runtime. In VB6, the CreateObject method would allow you to create an instance of an ActiveX object using its Prog ID.

 

In .Net, things are a little bit more complicated because objects have constructors. Before you can create an instance of an object, you have to choose which constructor to use.

 

Lets have two examples.

 

The first example will assume that the object in question implements a public constructor that has no parameters.

 

Public Shared Function CreateNew(ByVal ClassName As String) As Object

 

   Dim objType As System.Type

   Dim objConstructor As Reflection.ConstructorInfo

 

   ' no classname provided

   If ClassName Is Nothing Then Throw New ArgumentNullException("ClassName")

 

   ' find the type

   objType = Type.GetType(ClassName)

   If objType Is Nothing Then _

            Throw New Exception("Unknown Type " & ClassName)

 

   ' find the default constructor (the one that accepts no params)

   Dim objParams() As System.Type = {}

   objConstructor = objType.GetConstructor(objParams)

   If objConstructor Is Nothing Then _

            Throw New Exception("No default constructor for " & objType.FullName)

 

   ' invoke contsructor and return object

   Return objConstructor.Invoke(objParams)

 

End Function

 

 

Public Shared Sub Test()

 

   Dim objArray As ArrayList = CreateNew("System.Collections.ArrayList")

 

End Sub

 



0 comments, VB.Net, Wednesday, March 2, 2005 15:27

Timeline Navigation for VB.Net posts
VB.Net: How To Decode CSV Data using Regular Expressions (made 4 weeks later)
VB.Net: How To Creat an Instance of an Object using its Type Name (this post, made Wednesday, March 2, 2005 15:27)
VB.Net: Base64 Encoding and Decoding in One Line of Code (made 2 days earlier)


Comments

Post a Comment
Name:  Home page and email address are optional.
  Email addresses will not be displayed or spammed!
Remember these details
Email:
Home Page:
Comment:
Comments cannot contain HTML, URLs will be formatted into hyperlinks.
I reserve the right to remove any comments for any reason.