Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an object for a method call?

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.

like image 551
Shawn Avatar asked Dec 14 '11 22:12

Shawn


2 Answers

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.

like image 156
Mark Byers Avatar answered Nov 03 '22 00:11

Mark Byers


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.

like image 21
Ed S. Avatar answered Nov 02 '22 23:11

Ed S.