I’m trying to create an API in C# that uses method chaining. I want to ensure that at the end of the chain, a specific method (e.g., Throw()) is called. If this method is not called, an exception should be thrown.
Here is a simplified example of what I’m trying to achieve:
public interface IChainable
{
IChainable Step1();
IChainable Step2();
void Throw();
}
public class Chainable : IChainable, IDisposable
{
private bool _throwCalled = false;
public IChainable Step1()
{
return this;
}
public IChainable Step2()
{
return this;
}
public void Throw()
{
_throwCalled = true;
}
public void Dispose()
{
if (!_throwCalled)
{
throw new InvalidOperationException("Throw() method must be called when finishing the chaining");
}
}
}
However, I want to avoid this because it requires opening a using block, which is not desired in this case:
using (var chainable = new Chainable())
{
chainable.Step1().Step2();
// chainable.Throw(); // If the user forgets to call Throw(), an exception is thrown when the using block ends
}
I’m looking for a more robust and deterministic way to ensure that Throw() is called at the end of the chain, without having to use a using block. Is there any technique or pattern that can help me implement this more efficiently?
Any help is appreciated!
2
Answers
If I may suggest to the Finally block of Try-Catch-Finally block.
Regardless of the code execution getting into try or catch, you will always triggers the "Finally" block.
Hope this helps.
If you don’t have side-effects in those methods
Step1
andStep2
, but you are doing some form of building the final object, you can introduce another interfaceIFinishedChainable
that has methods relying on the state of the object after we callThrow
or whatever end method we need to complete the chaining. And then changeThrow
returnIFinishedChainable
instead ofvoid
.Complete example:
Then usage is: