Creating objects by name approach in .NET / C#

  • Thread starter Thread starter Rene
  • Start date Start date
R

Rene

We are moving from VB6 to C# and we like to know a good approach in .NET /
C# for this:

In VB6 we have some objects (classes) with the same interface, i.e. a to
control specific printers. Based on the configuration we load the correct
object that belongs to the attached printer (example code):

Dim obj as PrinterObject
Dim MyPrinter as String

MyPrinter = ReadPrinterFromDatabase ()
Set obj = CreateObject(MyPrinter)
obj.Print "Hello World"

IMO there are two ways:

a) Create different classes for each printer and create the class, but I
don't see a way how to do this (obj = new getPrinterClassName(); ???)
unless we use some Case or If Then code. Less flexible because adding
printers needs a modification in the code.
b) Create the object from a DLL by giving the DLL name (of .NET objects??)

I don't know if there are some '.net' ways to to this, in fact we wish to
add/install some DLL or object (with or without registering) without
terminating the application. Then we can change the configuration and the
new object is loaded when used.

Regards,

Rene
 
Hi Rene,

You may like to take a look at .NET Reflection for your requirements.
Refection allows you load classes dynamically by the name of the class type.
To get started, please take a look at Assembly.CreateInstance() or
Activator.CreateInstance().

Regards,
Aravind C
 
Have a XML file for your printer configuration, define in
that
<XML>
<Printer name ="HP Laserjet 1100" Assembly="HP1100.dll">
<xml>

and load the assembly on the run time using
reflection ... This way you added a layer for indirection
and adding new printer will not require recompile of your
whole code ..

Search MSDN for Activator to get the code to do the
reflection..

Sarosh
 
Thanks for you answer, I read something about reflection not knowing it can
be used for this.

Rene
 
Back
Top