private Vector2 ResolveCollision(ICollidable moving, ICollidable stationary)
{
if (moving.Bounds.Intersects(stationary.Bounds))
{
if (moving is Player)
{
(Player)moving.Color = Color.Red;
}
}
// ...
}
I have a class Player that implements ICollidable. For debugging purposes I’m just trying to pass a bunch of ICollidables to this method and do some special stuff when it’s the player. However when I try to do the cast to Player of the ICollidable I get an error telling me that ICollidable doesn’t have a Color property.
Am I not able to make a cast this way or am I doing something wrong?
I’d suggest using
asinstead ofis:The advantage is that you only do the type check once.
The specific reason why your code doesn’t work (as mentioned in other answers) is because of operator precedence. The
.operator is a primary operator which has a higher precedence than the casting operator which is a unary operator. Your code is interpreted as follows:Adding the parentheses as suggested by other answers solves this issue, but changing to use
asinstead ofismakes the issue go away completely.