0

I have recently started a development in c# and want to use reflection in following situation. If I have a Enum class as

Enum Operation
{
  Read=0;
  Write;
} 

If I give input as

String str = "Operation.Write";

I shoud be able to get output as 1;

Or

if constants are defined like

const int Read=0;
const int Write=1;

If the input is

String str = "Read";

output should be 0

Please Help.

3 Answers 3

3

You can use Enum.Parse to have that functionality.

If we combine your proposals we can get something like this.

public static Operation getOperationByName(String name)  {
    return Enum.Parse(typeof(Operation),name);
}

Where the name should not be null and represent the name or position in enum ie

"Read" will return Operation.Rerad and "1" will return Operation.Write

Sign up to request clarification or add additional context in comments.

Comments

1

Heres the complete code to also Get the type of the Enum through Reflection without hardcoding it. The ParseConstant Method is also generic, s.t. you can use if for every Type.

    namespace MyNamgespace
{
    public enum Operation
    {
        Read = 0,
        Write
    }

    public class ClassWithConstants
    {
        public const int Read = 0;
        public const int Write = 1;
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine((ParseEnum("Operation.Write")));
            Console.WriteLine((ParseContant<ClassWithConstants>("Write")));
            Console.ReadLine();
        }

        static int ParseEnum(string enumValue)
        {
            var typeName = enumValue.Split('.')[0];
            var valueName = enumValue.Split('.')[1];

            var enumType = Type.GetType(string.Format("MyNamespace.{0}", typeName));
            var op = (Operation) Enum.Parse(enumType, valueName);

            return (int)op;
        }


        static int ParseContant<T>(string constantName)
        {
            var type = typeof (T);
            var field = type.GetField(constantName, BindingFlags.Static | BindingFlags.Public);
            return (int)field.GetValue(null);
        }
    }
}

Comments

1

var name = Enum.GetName(typeof(Operation), Operation.Write) //name = 'Write'

var value = Enum.Parse(typeof(Operation), "Write") //value = Operation.Write

3 Comments

Why not just Operation.Write.GetName(); ?
that is the same method, it's a static method on the Enum type, that takes 2 arguments - a type, and a value.
Yes it is, my mistake with Java, there is normal, in C# you could create the extension.

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.