I have the following class hierarchy:
public class AI {
public AI() { }
public virtual void Update(float frameTime) { }
}
public class Boss : AI {
public Boss() : base() { }
public override void Update(float frameTime) {
Console.WriteLine("Boss Update");
}
}
I have a Character that holds an AI variable that I then store a Boss instance in and try to cast it as such to get the Boss's Update function rather than the base class's.
AI ai = new Boss();
(Boss)ai.Update(0f);
This doesn't work though, what is the proper method for doing this in C#? It was properly working with another AI class where I didn't even have to cast it at all, it just ran the right version of Update, so I must have changed something unintentionally.
The dot operator has higher precedence than casting, so your code is being interpreted as:
(Boss)(ai.Update(frameTime));
You need to add an extra pair of parentheses to get what you want:
((Boss)ai).Update(frameTime);
However it shouldn't be necessary to perform this cast since your method is virtual.
You may also want to consider changing your AI
type to be an abstract class
or (if possible) an interface.
You would need to add parens around the cast and the cast object to call the method on the cast value (i.e., ((SomeType)someObj).SomeMethod()
), but that is beside the point as the cast is completely unnecessary.
Update
is virtual and the call is polymorphic, so even though the ai
variable was declared as an instance of AI
it will actually call Boss.Update()
as that's what the type really is behind the scenes.
This is exactly why polymorphism is powerful. You don't have to know what the underlying type is to get the correct, implementation specific behavior.
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