Search code examples
c#parametersvirtualoverriding

CSharp virtual method and parameters


public abstract class State
{
public virtual Enter(/* THIS NEED A PARAMETER */)
{
// an empty method
}
}

public class PlayerState : State
{
public override Enter(Player pl)
{
// method implementation
}
}

public class GoalkeeperState : State
{
public override Enter(Goalkeeper gk)
{
// method implementation
}
}

//EXAMPLE OF USE
public State globalState;
globalState.Enter(owner);
// OWNER CAN BE PLAYER OR GOALKEEPER

I understand that the virtual and overriden methods need to have the same "print". So there is a design flaw here. So is something like this possible. How can I do this ? How would you do this?


Solution

  • You can use Generics here:

    public abstract class State<T>
    {
        public virtual Enter(T item)
        {
            // an empty method
        }
    }
    
    public class PlayerState : State<Player>
    {
        public override Enter(Player pl)
        {
            // method implementation
        }
    }
    
    public class GoalkeeperState : State<Goalkeeper>
    {
        public override Enter(Goalkeeper gk)
        {
            // method implementation
        }
    }