Interface and enum

A

Andrew Bainbridge

Hi,

I'm converting some code over from vb.net to c# and have the following
issue.

In VB you can have enum's within an interface. i.e.
Public Interface Class1
Enum ColorType
Black
Red
Yellow
White
End Enum
End Interface


You don't seem to be able to do this with c#.

i.e.
namespace ClassLibrary1
{
public interface Class1
{
public enum ColorType { Black, Red, Yellow, White };
}
}

This fails with:
Error 1 'ColorType': interfaces cannot declare types
D:\Dev\test\ClassLibrary1\Class1.cs 9 17 ClassLibrary1


It is valid in VB.Net to do this. If this can't be done where is the best
place to store the enum? Could you just bump it into the namespace? i.e.
namespace ClassLibrary1
{
public enum ColorType { Black, Red, Yellow, White };
public interface Class1
{
}
}


Just trying to understand what is best practice with enums and interfaces
under c#.

Would be good if someone who has an understanding of how the compiler
converts the VB.Net code to IL so I could implement it in a similar manner
in C#.


T.I.A.
 
M

Marc Gravell

Looking at the IL, it is pretty-much as per the VB... it just looks
like you can't do this directly in C# (similar to SomeRandomMethodName
implementing ISomeInterface.AnotherMethodName, which you can do in
VB.Net but not *directly* (i.e. as the IL level) via C#).

My personal view is that the next level up (typically namespace) is
fine for this scenario.

Marc
 
W

Wiebe Tijsma

Marc said:
Looking at the IL, it is pretty-much as per the VB... it just looks
like you can't do this directly in C# (similar to SomeRandomMethodName
implementing ISomeInterface.AnotherMethodName, which you can do in
VB.Net but not *directly* (i.e. as the IL level) via C#).

My personal view is that the next level up (typically namespace) is
fine for this scenario.

Marc

I usually make sure that nested types (classes/structs/enums) are
protected or private most of the time (there are some exceptions), and
in that perspective there's no use to include these kind of types in an
interface.

Best Regards,

Wiebe Tijsma
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

No, you cannot do that in C#, promoting it to the namespace is the only way
to do it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top