(Probably obvious) .NET question - creating objects dynamically

  • Thread starter Thread starter Jethro
  • Start date Start date
J

Jethro

Hi all,

I have a solution, which contains several projects. Each project occupies
the same namespace, and compiles to s different .NET DLL

e.g.

MyNamespace.ThisClass is in one DLL
MyNamespace.ThatClass is in another DLL

I wish for a .NET EXE to be able to dynamically create an instance of either
on of the classes, given the classes name as a string.

I have tried using System.Reflection.Assembly calls, but watching in debug,
the Load call fails.

What would the mechanism be for doing this ?

thanks in advance.
 
* "Jethro said:
I have a solution, which contains several projects. Each project occupies
the same namespace, and compiles to s different .NET DLL

e.g.

MyNamespace.ThisClass is in one DLL
MyNamespace.ThatClass is in another DLL

I wish for a .NET EXE to be able to dynamically create an instance of either
on of the classes, given the classes name as a string.

I have tried using System.Reflection.Assembly calls, but watching in debug,
the Load call fails.

\\\
Private Function CreateClassByName( _
ByVal PartialAssemblyName As String, _
ByVal QualifiedClassName As String _
) As Object
Return _
Activator.CreateInstance( _
[Assembly].LoadWithPartialName( _
PartialAssemblyName _
).GetType(QualifiedClassName) _
)
End Function
///

Usage:

\\\
Dim c As Control = _
DirectCast( _
CreateClassByName( _
"System.Windows.Forms", _
"System.Windows.Forms.Button" _
), _
Control _
)
With c
.Location = New Point(10, 10)
.Size = New Size(80, 26)
.Text = "Hello World"
End With
Me.Controls.Add(c)
///
 
Jethro,
A variation of the Activator.CreateInstance that I normally use.

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