Haven't access to class in custom class stack implementation

My classes structure looks like:

public abstract class LogicalTreeNode {
}

public class LogicalOperator:LogicalTreeNode {
    public readonly string value;

    public LogicalOperator(string value) {
        this.value = value;
    }

}

public class ConditionResult:LogicalTreeNode {
    public readonly bool value;

    public ConditionResult(bool value) {
        this.value = value;
    }
}`

I'm trying to implement some logic with using Stack<LogicalTreeNode>. I need standart stack's methods and my own TryPush(LogicalTreeNode), that will work recursive (for some cases). So i do that:

public class Stack<LogicalTreeNode> : Stack {
    public void TryPush(LogicalTreeNode logicalTreeNode) {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

And i get cannot convert ConditionResult to LogicalTreeNode. What am i doing from? TIA.

Upvotes: 3

Views: 62

Answers (1)

Souvik Ghosh
Souvik Ghosh

Reputation: 4616

You have created a custom class Stack generic to System.Collections.Stack which accepts Stack<LogicalTreeNode>.

Change your code to this-

public class Stack<T> : Stack
{
    public void TryPush(LogicalTreeNode logicalTreeNode)
    {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

If you specifically want your class to be instantiated with only certain type like- LogicalTreeNode in this case, then you have to do like this-

public class MyStack<T> where T : LogicalTreeNode
{
    public void TryPush(LogicalTreeNode logicalTreeNode)
    {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

If you need to inherit from System.Collections.Stack class and also restrict the type to LogicalTreeNode, then do like this-

public class MyStack<T> : System.Collections.Stack : where T : LogicalTreeNode
{
    public void TryPush(LogicalTreeNode logicalTreeNode)
    {
        /*Some logic */
        this.TryPush(new ConditionResult(false));
    }
}

Also, as a good practice, don't name your class as Stack as it is a C# keyword. Use a different name.

References:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-classes

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters

Upvotes: 1

Related Questions