trying to implement observer by using delegate i get the error : cannot implicitly convert type 'void' to the class where my delegate belong to

// subject 
class SafeMode
{
    private bool m_enable = false;
    public bool Disable()
    {
        return m_enable;
    }

    public delegate void NotifyObserversHandler(bool _status);

    public event NotifyObserversHandler DiableCommands;

    public void Notify()
    {
        DiableCommands(m_enable);
    }
}


public interface ICommand
{
    void Execute(User i_User, string i_ButtonText, List<Photo> o_Photos);
    void DiableFunctionality();
}

// my only observer
public class MostPopularPic : ICommand
{
    public void DisableFunctionality()
    {
        m_enable = false;
    }
}


// at other form class that's where i  attach my observer to the delegate and the error occurs. 
foreach( KeyValuePair<string,ICommand> runner in tmp)
{
    ICommand curr = runner.Value;
    m_safer.DiableCommands += curr.DiableFunctionality();
    // faild to convert 'void' to  'SafeMode.NotifyObserversHandler' 
}
Jon Skeet
people
quotationmark

Look at this statement:

m_safer.DiableCommands += curr.DiableFunctionality();

That's trying to invoke curr.DiableFunctionality and then subscribe the result of the method call to the m_safer.DiableCommands event.

You don't want to invoke the method now - you just want to convert the method group to a delegate, and subscribe that delegate. So you want:

m_safer.DiableCommands += curr.DiableFunctionality;

That will still have a problem though - your DiableFunctionality method is parameterless, whereas your NotifyObserversHandler delegate has a bool parameter. If you want to just ignore that parameter, you could use:

m_safer.DiableCommands += ignored => curr.DiableFunctionality();

This now uses a lambda expression which takes a single parameter (ignored) and ignores it, just calling curr.DiableFunctionality().

people

See more on this question at Stackoverflow