0

How to use enum datatype in interface?

Is this possible?

public interface IParent1
{
    string method1(Test enum);
}

public class Parent1 : IParent1
{
    public enum Test 
    {
        A, 
        B, 
        C
    }

    public string method1(Test enum)
    {
        return enum.ToString();
    }
}
1
  • What happened when you tried? (it's not possible to use keywords as identifiers though, (unless they are prefixed with '@') Commented Sep 28, 2011 at 7:21

3 Answers 3

10

enum is a reserved keyword in C#. You can prefix it with @ if you want to use it as variable name:

public enum Test { A, B, C };

public interface IParent1
{
    string method1(Test @enum);
}

public class Parent1 : IParent1
{
    public string method1(Test @enum)
    {
        return @enum.ToString();
    }
}

But I don't like using reserved words for variable names. A better approach would be:

public enum Test { A, B, C };

public interface IParent1
{
    string method1(Test test);
}

public class Parent1 : IParent1
{
    public string method1(Test test)
    {
        return test.ToString();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or better yet, for clarity and readability, change the name of the argument to something that is not a reserved word in C# (or preferably in any .NET language in general).
0

Don't see any problem with that. But why do you nest your enum declaration in the interface implementation? Your code will not compile, because: 1. You're using reserved word enum 2. value is not declared

Try use this:

public enum Test { A, B, C };

public interface IParent1 { string method1(Test @enum);}

public class Parent1 : IParent1
{
    public string method1(Test @enum)
    {
        return @enum.ToString();
    }
}

Comments

0

If you want your enum to be different in each implementing class you should use a generic interface like

public interface MyInterface<T>
{
    string MyMethod(T myEnum)
}

If it should be the same for all implementing classes just don't put it outside any class:

public enum MyEnum { A, B, C }

public interface MyInterface
{
    string MyMethod(MyEnum myEnum)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.