Search code examples
c#eventsbooleaniterationreturn-type

func<bool> events and a headache


I have a boolean event, and I am trying to call each subscriber individually so I can return false if even one subscriber returns false. So far, my attempts have left me with nothing but a brain that is tired, wants to cry, and eat a pop tart(then cry some more).

For the function that actually calls the event, I have been doing this:

foreach (Delegate sub in SomeBooleanEvent.GetInvocationList())
             {
                 someBool = sub;
                 //blah blah blah code blah blah blah
                 }
             }

The error I get is:

CS0029: Cannot implicitly convert type 'System.Delegate' to 'bool'

I am so confused...help me...please...🥺

Edit: After finally managing to muster the willpower to tackle this, I have found using func<bool> instead of Delegate seems to partially work.

However, I now have a new problem. When I call the event, only one subscriber is present/called?


Solution

  • I finally figured out what was going on. For those that may find this useful, func<bool> should be used instead of Delegate(the code I made before my last edit didn't call subscriber because I had accidentally deleted a code block that would have called each method).

    By simply doing

    public event Func<bool> onAWildBooleanEvent;
    
    public bool? AWildBooleanEVent(){
                bool? result = null;
                if(daBool!=null){
                    foreach (Func<bool> sub in onAWildBooleanEvent.GetInvocationList())
                    {
                        if(result == null){
                            result = sub();
                        }else{
                            if(sub()!=result){
                                result= false;
                            }
                        }
    
                    }
                    return AoNBool;
                }
                return null;
            }  
    

    This should work for other types as well as long as you have no need for event handlers and event args. Just make sure you set the func to the appropriate type. Also, if you want all events to trigger, make sure to call them. Otherwise, they will not be notified of the event.