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:
You need to add an extra pair of parentheses to get what you want:
However it shouldn’t be necessary to perform this cast since your method is virtual.
You may also want to consider changing your
AItype to be anabstract classor (if possible) an interface.