C#
Hi all,
I pass an object to a method.
I want to cast that object to its specific class so I can perform its own specific methods? How can I do that?
Move( new Cat() );
Move( new Pigeon() );
public void Move(object objectToMove)
{
if(objectToMove== Cat)
{
Cat catObject = objectToMove as Cat;
catObject.Walk();
}
else if(objectToMove== Pigeon)
{
Rat pigeonObject = objectToMove as Pigeon;
pigeonObject.Fly();
}
}
The right way to do this would be:
public interface ICanMove
{
void Move();
}
implemented by both Cat and Pigeon:
public class Cat : ICanMove
{
public void Move() { /* do something */ }
}
public class Pigeon : ICanMove
{
public void Move() { /* do something */ }
}
And then call it like this:
public void Move(ICanMove objectThatMoves)
{
objectThatMoves.Move();
}
You gain several things:
Move(ICanMove objectThatMoves)
for an object that implements the interface. If you try to pass a different object, your program will not compile.Dog
which implements ICanMove
to your program, the Move method will work great without any modifications. In your version you will have to change the method.Imagine how much work you would have if you had is
statements all over your program?
Well, you can use the is
keyword like this:
if(objectToMove is Cat)
{
...
}
else if(objectToMove is Pigeon)
{
...
}
One small point... It's more correct to not use as and is together as the second type check implied is redundant. Either use as in the following manner:
Cat catObject = objectToMove as Cat;
if(catObject!=null)
catObject.Walk();
else
{
Pigeon pigeonObject = objectToMove as Pigeon;
if(pigeonObject!=null)
pigeonObject.Fly();
}
Or do a direct cast as you are sure it will succeed; this is both more efficient and more clear:-
if(objectToMove is Cat)
{
Cat catObject = (Cat)objectToMove;
catObject.Walk();
}
else if(objectToMove is Pigeon)
{
Pigeon pigeonObject = (Pigeon)objectToMove;
pigeonObject.Fly();
}
Using a direct cast you get an exception if it fails, rather than a null. People reading the code will know without context "We're not just trying to see if it can be treated as
something, we're sure that we've ascertained that it should be possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With