Variable for Casting?

J

James Scott

Hello,

my question is, if it's possible to "dynamical" cast?

at the moment my print() method looks like this:

public void print(Object obj) {

if (obj is TypeA)
((TypeA)obj).print();
if (obj is TypeB)
((TypeB)obj).print();
if (obj is TypeC)
((TypeC)obj).print();
if (obj is TypeD)
((TypeD)obj).print();
......
}


and I was wondering if it's possible to shorten it, like

PseudoCode:
public void print(Object obj) {

String typeOfObject = obj.getType();
((typeOfObject)obj).print();

}


Thanks!
 
M

Mythran

James Scott said:
Hello,

my question is, if it's possible to "dynamical" cast?

at the moment my print() method looks like this:

public void print(Object obj) {

if (obj is TypeA)
((TypeA)obj).print();
if (obj is TypeB)
((TypeB)obj).print();
if (obj is TypeC)
((TypeC)obj).print();
if (obj is TypeD)
((TypeD)obj).print();
.....
}

I don't believe so...doing something like that though..you would think an
interface or base class (that contains print) would be passed to the print
method instead:

interface IMyInterface
{
void print();
}

class TypeA {
public IMyInterface.print() { // Can't remember if this is correct.
// print here
}
}

class TypeB {
public IMyInterface.print() {
// print here
}
}

public void print(IMyInterface obj) {
obj.print();
}

public void DoSomething()
{
IMyInterface obj = new TypeA();
TypeB obj2 = new TypeB();

print(obj);
print(obj2);
}



HTH,
Mythran
 
I

Ignacio Machin \( .NET/ C# MVP \)

hi,

You have several solutions

Listed in prefered order

1- Use an interface :
interface IPrint
{
print();
}

so each class will implement it, your method will change to:

public void print( IPrint p)
{
p.print();
}

the best part of tis solution is that ou do not need to modify the current
class inheritance structure.

2- Make a common parent and implement there the print method, then derive
all types from it.

3- Use reflection
You can know the method a class provide and you can call one.

print( object o )
{

o.GetType.GetMethod("print").Invoke( o, null );

}

you may have to change the above code to check for error if the method print
does not exist, otherwise you can get an exception


cheers,
 

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