Click here to Skip to main content
15,911,503 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a situation where I find myself needing to call methods that reside in the caller class. Should i pass 'this' as a parameter, as I've done below, or should I be raising events back up to the caller? Or is there another way that this is normally done?

What I have tried:

The example below works, but feels a bit dirty. I feel like there should be a better way.

C#
void Main()
{
	var stack = new Stack();
	stack.Push(1);
	stack.Push(2);
	stack.Push(3);
	stack.Push(4);
	
	var specialStack = new SpecialStack(stack, new TriplePopper());
	specialStack.SpecialPop();
	// stack now only has a count of 1
}

public class SpecialStack
{
	IPopper _popper;
	Stack _stack;

	public SpecialStack(Stack stack, IPopper popper)
	{
		_stack = stack;
		_popper = popper;
	}

	public void SpecialPop()
	{
		_popper.SpecialPop(this);
	}

	public void PopOnce()
	{
		_stack.Pop();
	}

}

public interface IPopper
{
	void SpecialPop(SpecialStack stack);
}

public class DoublePopper : IPopper
{
	public void SpecialPop(SpecialStack stack)
	{
		stack.PopOnce();
		stack.PopOnce();
	}
}

public class TriplePopper : IPopper
{
	public void SpecialPop(SpecialStack stack)
	{
		stack.PopOnce();
		stack.PopOnce();
		stack.PopOnce();
	}
}
Posted
Updated 17-Aug-20 22:10pm
v3

Raise events back up to the caller: a class should never know who or what called it, so it shouldn't access methods in them. If you do, you lock the design together so that both you can't change one without considering the effects on the other, and you can't reuse the classes independently.
 
Share this answer
 
I think what you want to do here can be done so much more simply by extending the 'Stack Class:
C#
using System.Collections.Generic;
using System.IO;

namespace WFTemplate_Aug2020
{
    public class StackPopEx<T> : Stack<T>
    {
        public StackPopEx(params T[] values)
        {
            foreach(T itm in values) Push(itm);
        }

        public void PopEx(int npops)
        {
            if (npops <= 0)
            {
                throw new InvalidDataException($"npops = {npops}  <= 0");
            }

            if (npops > Count)
            {
                throw new InvalidDataException($"npops = {npops} greater than stack count: {Count}");
            }

            for (int i = 0; i < npops; i++)
            {
                Pop();
            }
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900