3

I am trying to invoke an event in the interface in which it is defined (see code below). However, I get the following error: Program.cs(7,3): error CS0079: The event 'IMyInterface.MyEvent' can only appear on the left hand side of += or -=.
I suspect it might have something to do with all events declared in interfaces are always properties. Is this a bug, a feature, and are there any workarounds?

Thanks.

using System;
public interface IMyInterface
{
    event EventHandler? MyEvent;
    void CallMyEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

public class MyClass : IMyInterface
{
    public event EventHandler? MyEvent;
}
static class Program
{
    static void Main()
    {
        var obj = new MyClass();
        obj.CallMyEvent();
    }
}
  • 4
    You really shouldn't be doing that inside the interface anyway. – DavidG Dec 09 '21 at 14:18
  • 4
    Why are you writing implementation code in your interface? I know it's a new feature of c#, but, why? – gunr2171 Dec 09 '21 at 14:19
  • It looks like you're right about the event in the interface only being the add/remove api without a backing field https://github.com/dotnet/csharplang/discussions/2928 – juharr Dec 09 '21 at 14:27
  • Make `CallMyEvent` a regular interface defined method. Create an abstract implementing IMyInterface. Put the `CallMyEvent` impl in there. Change to `MyClass : MyAbstract`. – AndyPook Dec 09 '21 at 14:38
  • 1
    You can only do inside a default implementation what an external consumer of the interface can do (which is after all the position the default implementation is in w.r.t. any actual implementation) – Damien_The_Unbeliever Dec 09 '21 at 14:47

2 Answers2

2

I think it's because event EventHandler? MyEvent not implemented inside your interface, it will be implemented inside your class and after it, you can Invoke it:

public class MyClass : IMyInterface
{
    public event EventHandler? MyEvent;

    public void CallMyEvent()
    {
        MyEvent?.Invoke(this, EventArgs.Empty);
    }
}

After C# 8 you actualy can do default implementation of methods inside interface, but only methods, not events.

If you want predefined method, that will call event, you can make abstract class instead of interface.

Karoshee
  • 158
  • 8
0

It appears that the only way around this problem is to invoke the event outside the interface. Either use an abstract class that I was trying to avoid, or have a regular interface method and give up DRY code.