0

I have a generic interface, which looks like this:

public interface IObjectProvider<out T>
{
    event Action<T> ValueOccured;
}

Now I want to make a class, which implements this interface two times like this:

public class GlobalReceiver : IObjectProvider<Foo>, IObjectProvider<Bar>
{
    public event Action<Foo> IObjectProvider<Foo>.ValueOccured;

    public event Action<Bar> IObjectProvider<Bar>.ValueOccured;
}

and can't get it working, because for this compiler says that I need to use proper syntax and if I make non-explicit implementation I (as expected) get an error:

Member is already declared.

How can I figure out this problem?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Alex Voskresenskiy
  • 2,143
  • 2
  • 20
  • 29

2 Answers2

8

You have to explicitly tell how to implement the add and remove on the event, since it is an explicit interface implementation:

public class GlobalReceiver : IObjectProvider<Foo>, IObjectProvider<Bar>
{
    private event Action<Foo> ActionFoo;

    event Action<Foo> IObjectProvider<Foo>.ValueOccured { add { ActionFoo += value; } remove { ActionFoo -= value; } }

    private event Action<Bar> ActionBar;

    event Action<Bar> IObjectProvider<Bar>.ValueOccured { add { ActionBar += value; } remove { ActionBar -= value; } }
}

I added a default implementation that you might use for the actual events to make them accessible from your class.

Why? Probably because you can't call the event from just the member name in your class, so it will be very hard to call the event handler.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

Explicit interface implementations can't be public. Remove the public accessor.

Also, as explained in How to: Implement Interface Events (C# Programming Guide):

When you write an explicit interface implementation for an event, you must also write the add and remove event accessors.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272