Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Casting an 'object' parameter into that object's type?

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();
    }
}
like image 263
divinci Avatar asked Nov 03 '09 10:11

divinci


3 Answers

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:

  1. You can only call the Move(ICanMove objectThatMoves) for an object that implements the interface. If you try to pass a different object, your program will not compile.
  2. You lose the conditional statement. If you decide to add a 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?

like image 79
Groo Avatar answered Oct 04 '22 04:10

Groo


Well, you can use the is keyword like this:

if(objectToMove is Cat)
{
    ...
}
else if(objectToMove is Pigeon)
{
    ...
}
like image 37
Yogesh Avatar answered Oct 04 '22 03:10

Yogesh


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.

like image 40
Ruben Bartelink Avatar answered Oct 04 '22 04:10

Ruben Bartelink