Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

480
Visualizações
Invoke c# event inside interface

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();
    }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda