Type Casting

A

Analizer1

Hi All...
i have a situation where i have 3 different Types (classes)
comming into a controling Class to Run Different Jobs
in my main loop i want to use 1 Field to hold a instance of the Class
currently Running example below

public class controler(
{
// how to use the below process for all 3 different Type?
// this is ccalled each time a run is started in
//different threads from the service
//i want to use one field to hold the current Process
//instead of using 3 Fields and if block
private Process
public controler(int iToRun)
{
if (iToRun==1)
{
Process = new Object1() ;
}
else if (iToRun==2)
{
Process = new Object2();
}
else
{
Process = new Object3();
}
}
public int Runjob()
{
int iRet=0;
if ( (iRet=Process.Execute())<=0)
{
//error occurred
}
else
{
//success
}
}
}

Tia
Analizer1
 
J

Jon Skeet [C# MVP]

Analizer1 said:
i have a situation where i have 3 different Types (classes)
comming into a controling Class to Run Different Jobs
in my main loop i want to use 1 Field to hold a instance of the Class
currently Running example below

Create an interface (e.g. IExecutable) with all the methods that the
different types have in common (e.g. Execute()) and make all of the
types implement that interface.
 
N

Nicholas Paldino [.NET/C# MVP]

Analizer1,

You should have all three objects implement a shared interface, and then
cast the objects to an instance of that interface. Then, you can call the
methods on the interface.

You could do this with reflection, but that's just messy.
 
S

sloan

Do a search on the "Command Design Pattern" as well, to learn some
caveats............
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top