Share via


enums inside interface ?

Question

Wednesday, February 28, 2007 8:31 AM

What is the way to involve enums in an interface?

i know why i can't , but how do i solve this ?

public interface ICommCallback

{

      enum CommEvents       // ERROR!

      {

          Connect,

          Disconnect,

          Send

       }

       void handleReceiveCB(byte[] ReceivedData);

       void handleEventCB(CommEvents commEvent, bool Res);

}

All replies (4)

Wednesday, February 28, 2007 9:39 AM ✅Answered

Hi rodniko!

You have to define the enum outside of the interface.

greets,
Roland


Wednesday, February 28, 2007 9:39 AM ✅Answered

Why are you trying to put an enum definition into an interface? Interface is kind of a contract. 

You should put your enum outside the interface:

public interface ICommCallback

{

       void handleReceiveCB(byte[] ReceivedData);

       void handleEventCB(CommEvents commEvent, bool Res);

}

public  enum CommEvents    

      {

          Connect,

          Disconnect,

          Send

       }


Wednesday, February 28, 2007 3:13 PM | 1 vote

VB allows declaring enums (and other types) inside of an interface, but C# does not.

David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C# to C++ converter, VB to C++ converter
Instant Python: C# to Python converter, VB to Python converter


Monday, February 6, 2012 9:52 AM | 9 votes

I would think the reason is obvious: The enum is used only for that interface, and so should be scoped inside the interface namespace. Having to put the enum outside the interface causes clutter in the containing namespace.

I'd like to see some best practices to avoid such clutter. I see the following options:

1. Put both the interface and the enum inside a namespace for that particular interface.
Pros: Good scoping of related names inside a common namespace.
Cons: Namespace proliferation.

2. Create a separate static class or namespace for the enum.
Pros: Avoids clutter in the containing namespace.
Cons: Also namespace proliferation and possible name clash between the class/namespace and the default interface implementor, e.g. MyNamespace.ICustomerService would have enum MyNamespace.CustomerService.ProcessingMode, but the default service implementation would likely also be named MyNamespace.CustomerService (unless it would be OK with MyNamespace.DefaultCustomerService). Frankly, it all turns into a bit of a mess.

3. Prefix the enum name with the service name, e.g. for ICustomerService you may have enum CustomerServiceProcessingMode.
Pros: Reduces the risk of name clashes in the containing namespace as well as namespace proliferation.
Cons: Ugly and cumbersome names.

So what would you recommend?