dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.29k stars 5.92k forks source link

dotnetstandard 2.1 c# 8 and The event can only appear on the left hand side of += or -= #18223

Closed ghost closed 4 years ago

ghost commented 4 years ago

I'm using dot net standard 2.1 and c# 8, I want to create an event for my class (interface), I follow this tutorial and I wrote an interface:

using System;
using Crawler.Paging;

namespace Crawler
{
    public interface ICrawler
    {
        public event EventHandler NextPage;
        protected virtual void OnNextPage(EventArgs e)
        {

            EventHandler handler = NextPage;
            handler?.Invoke(this,e);
        }
        void Paging(IPaging paging);
    }
}

but take me an error:

Error The event 'ICrawler.NextPage' can only appear on the left hand side of += or -=

I proceeded with this training, so where is the problem? stackoverflow link

IEvangelist commented 4 years ago

Hi @djary,

Thank you for posting this issue. You're actually deviating from the tutorial, in the tutorial it shows how to use events with a class. Instead, you're attempting to use an interface with a default method implementation. This happens when using a default method implementation with an interface. If you change from an interface to a class, like demonstrated in the tutorial this will work. As of right now, accessing event members in default interface methods is not supported.

More information on this here, and more specifically.

gafter commented on Nov 4, 2019 This is by design. Your event is abstract. As such it has no backing field or implementation. There is no value for you to invoke.