0
public abstract class Problem
{
    public abstract List<Action> GetPossibleActions(State currentState);
}

Here both Action and State classes are also Abstract Classes.

In the child class of Problem, I am implementing that abstract method with using children of Action and State. Now it gives me error because I didnt use the same Abstract classes for return type and argument.

public class PizzaProblem : Problem
{
    public List<PizzaAction> GetPossibleActions(PizzaState currentState)
    {
       ......
    }

}
hikariakio
  • 21
  • 2
  • 1
    `Problem p = /* Some child class, who knows which one */; p.GetPossibleActions(/* Any possible state derived class, not necessarily related to the previous child */);`. Do you see the problem? – Damien_The_Unbeliever Aug 18 '22 at 06:31
  • Does this answer your question? [Does C# support return type covariance?](https://stackoverflow.com/questions/5709034/does-c-sharp-support-return-type-covariance) – Charlieface Aug 18 '22 at 10:26

2 Answers2

1

You could make your class a generic class:

public abstract class Problem<TAction, TState>
  where TAction : Action
  where TState : State
{
    public abstract IList<TAction> GetPossibleActions(TState currentState);
}

public class PizzaProblem : Problem<PizzaAction, PizzaState> { ...

Or don't care about the concrete type contained in your list: rely on polymorphism to call the correct methods.

knittl
  • 246,190
  • 53
  • 318
  • 364
  • Additionally you can add general type constraints for `TAction` and `TState` to force them to implement `Action` and `State`. – Qwertyluk Aug 18 '22 at 06:48
  • How should I pass the Argument? `SomeMethod(Problem problem) ; ` `pprob = new PizzaProblem();` now it shows me an error when i call. `SomeMethod(pprob);` @knittl – hikariakio Aug 18 '22 at 08:24
  • @YeGaung right. In that case, you need to define an interface with co-/contravariant generic types. But I think that this approach might not be the best for your problem at hand. Why do you need to know the concrete types and cannot rely on polymorphism? – knittl Aug 18 '22 at 08:31
  • @knittl I just changed my code to a normal simple way, now. Now my code has a lot of casting. Is that normal? – hikariakio Aug 18 '22 at 08:43
  • @YeGaung what is a "normal, simple way"? – knittl Aug 24 '22 at 05:27
0

The signature needs to stay the same way as in the abstract class. Try

public List<Action> GetPossibleActions(State currentState)
{
    // Your code
}

Also Action is an object for it self. If you didn't define the PizzaAction type which inherits from action, it won't work. Same is valid for State.

Patrick
  • 387
  • 3
  • 15