Search code examples
c#fluent-interfacemethod-chaining

How create Fluent Interface in C# with some limitation for some methods?


See below codes :

new ConditionCreator()
       .Add()
             .Or()
       .Add()
             .And()
       .Add()

I want to create a Fluent Interface for that But I need, after Add() method developer see Only Or() or And() and after one of these, see Only Add() method.

so no one can write a code like :

new ConditionCreator()
           .Add()
           .Add()
           .Add()
           .Or()
           .And()
           .Add()
           .And()
           .And()

I want to have a limitation for some methods can accept special methods and etc. I can write all methods in one class and return this for each one but that is not suitable !!!

Please guide me How write Advanced Fluent Interface class.


Solution

  • Consider returning an interface that contains only And() and Or(). For example:

    public class ConditionCreator : IFluentAndOr
    {
        public IFluentAndOr And() { ... }
        public IFluentAndOr Or() { ... }
    }
    
    public interface IFluentAndOr
    {
        IFluentAndOr And();
        IFluentAndOr Or();
    }