Creating dynamic objects

  • Thread starter Thread starter Jakob Lithner
  • Start date Start date
J

Jakob Lithner

I have searched the news groups on similar subjects, but
haven't found anything adequate for my need ....

To save much duplication of code I would like to create a
baseclass that takes a SQL-Select-string and a type as
parameters. It will then return a collection of objects of
the specified type. (I have ~30 object types that will be
fetched in exactly the same way from one table each).

Dynamic parsing works fine using the Reflection namespace,
but the instantiation of objects seems to be tricky.

I would like to do something like:


Private Shared Function GetMessage(ByVal myType As
System.Type, ByVal collectionType As
IMessageCollectionBase, ByVal strSQL As String) As
Collection

Dim o as object

'Call DB and get datareader ...

While dr.read()
o = New myType
o.Parse(dr)
collectionType.Add(o)
End While

Return collectionType

End Function



Is it possible at all?
 
If each of your types does implement the a specific interface with the Parse method, all you need to do is to just create the type dynamically using reflection and use the interface to parse the data reader into the object and add it to the collection.

Rgds,
Anand
VB.NET MVP
http://www.dotnetindia.com
 
Jakob,
The following should work for you, in your case instead of reading the type
from ConfigurationSettings.AppSettings (app.config file), I would read it
from a field in the database table.

I use System.Type.GetType to return a Type object for the concrete class I
want (determined via the app.config). The strings in the app.config should
to be in "myproject.myclass, myassembly" format.

I use System.Activator.CreateInstance to create an instance of the concrete
class.

' VB.NET sample
Dim s As String
s = ConfigurationSettings.AppSettings("myplugin")

Dim t As Type
t = Type.GetType(s)

Dim obj As Object
obj = Activator.CreateInstance(t)

' Or if you want to pass parameters to the constructor
obj = Activator.CreateInstance(t, New Object() {p1, p2})
' the above calls the constructor that has two parameters.
' there are 7 or so overloads of CreateInstance,
' if you have default constructors or other needs

Dim plugin As MyPlugInBase
plugin = DirectCast(obj, MyBaseClass)

I use this in a couple of projects, works very well.

Hope this helps
Jay
 
Back
Top