Reputation: 83
I have an interface
Interface:
interface IThing
{
Enum MyEnum {get;set;}
string DoAction(MyEnum enumOptionChosen, string valueToPassIn);
}
Concrete implementation:
public class Thing : IThing
{
public enum MyEnum
{
FirstOption,
SecondOption,
ThirdOption
}
string doAction(MyEnum enumOptionChosen, string valueToPassIn)
{
switch(enumOptionChosen)
{
case MyEnum.FirstOption:
x();
break;
case MyEnum.SecondOption:
y();
break;
case MyEnum.ThirdOption:
z();
break;
}
}
}
When I try compiling this I get 'IThing.MyEnum' is a 'property' but is used like a 'type.' I'm missing something about being able to require use of the Enum in the DoAction() signature.
Thanks for any help.
Upvotes: 8
Views: 31224
Reputation: 295
I realize the original post is very old, but this is another approach that is clear and works well. Since the Enum is public, just go ahead and define it outside of the concrete class and the interface. (I've taken the liberty of renaming the enum type to TheEnum to avoid confusion with the property MyEnum.)
public enum TheEnum
{
FirstOption,
SecondOption,
ThirdOption
}
Then reference it in your interface and concrete class.
public interface IThing
{
TheEnum MyEnum { get; set; }
string DoAction(TheEnum enumOptionChosen, string valueToPassIn);
}
public class Thing : IThing
{
public TheEnum MyEnum { get; set; }
public string DoAction(TheEnum enumOptionChosen, string valueToPassIn)
{
return "Something";
}
}
Upvotes: 1
Reputation: 40235
In your interface MyEnum
is the name of the variable not the type, so it won't be recognized by the compiler. You should be able to use Generics to get this done.
public interface IThing<T>
{
T MyEnum { get; set; }
string doAction(T enumOptionChosen, string valueToPassIn);
}
Then you could implement it like this:
public interface IThing<T>
{
T MyEnum { get; set; }
string doAction(T enumOptionChosen, string valueToPassIn);
}
public class Something : IThing<Something.SpecialEnum>
{
public enum SpecialEnum
{
Item1,
Item2,
Item3
}
public SpecialEnum MyEnum { get; set; }
public string doAction(SpecialEnum enumOptionChosen, string valueToPassIn)
{
return "something";
}
}
Upvotes: 17
Reputation: 73102
Firstly, declare your enum outside of the interface/concrete.
Then in your interface:
MyEnum SomeNum {get; set;}
Then in your class:
public MyEnum SomeNum
{
get
{
...
}
set
{
...
}
}
Your main problem was you were trying to declare a return type of "Enum" from your interface, when you should be declaring a return type of "MyEnum".
Remember, enum is a type. You can't force a class to implement a "type", only properties/methods.
That being said, i'm scratching my head to try and figure out what you are trying to do.
Upvotes: 3