You may receive a CS0117 compiler error when you explicitly implement an interface event

Symptoms

You can implement interface events in a class explicitly. However, when you implement interface events explicitly, and you instantiate the class instance, you may receive the following compiler error message:
error CS0117: 'namespace. class name' does not contain a definition for Interface name'

Cause

When a class explicitly implements events of an interface, explicitly implemented events are not accessible from class instances.

Workaround

To work around this problem, create an instance of the interface, and then access the events.

Use the following code to create an instance of the interface to access events:
IMyInterface eventSample = new ExplicitEventSample();
eventSample.MyEvent += new MyDelegate(FindLength);

Status

This behavior is by design.

More Information

Steps to Reproduce the Behavior

  1. Paste the following code in Notepad:
    using System;

    namespace EventTest
    {
    public delegate int MyDelegate(string s);

    public interface IMyInterface
    {
    event MyDelegate MyEvent;
    }

    public class ExplicitEventSample: IMyInterface
    {
    event MyDelegate IMyInterface.MyEvent //Explicit implementation of IMyInterface.MyEvent
    {
    add
    {
    MyEvent2Storage += value;
    }
    remove
    {
    MyEvent2Storage -= value;
    }
    }

    public MyDelegate MyEvent2Storage; // underlying storage for IMyInterface.MyEvent.

    }

    class Class1
    {
    [STAThread]
    static int FindLength(string strArg)
    {
    return strArg.Length;
    }

    static void Main(string[] args)
    {
    ExplicitEventSample eventSample = new ExplicitEventSample();

    eventSample.MyEvent += new MyDelegate(FindLength);

    }
    }
    }
  2. Save the file as
    c:\Sample.cs.
  3. At the Visual Studio .NET command prompt, run the following command to compile the code:
    csc c:\Sample.cs
You may receive the compilation error that is mentioned in the "Symptoms" section of this article.

References

For more information about explicit interface implementation, see the following Microsoft Developer Network (MSDN) Web site:
Explicit Interface Implementation Tutorial
http://msdn2.microsoft.com/en-us/library/Aa288461(VS.71).aspx
Propriedades

ID do Artigo: 821175 - Última Revisão: 11 de jul de 2008 - Revisão: 1

Comentários