0

So,

Just to be clear, I have already viewed this Q&A and this is not my question.

Now, my question is, I have a string that I'm able to extract from Excel and break it down by splitting and other methods and find whether it is an enum or not.

For example:

string enumStr = "eSomeEnumObject RANDOMENUMVAL" 

is the string and I'm able to split and check if it is an enum and get a string array as such:

string[] enumArr = { "SomeEnumObject", "RANDOMENUMVAL" };

Now, I need to use it in a class TestClass which references a library which contains various method definitions and enums as well. The enum object name and value that I've just extracted basically already exists there. Now, I know that to convert a string to enum value we use something like this:

SomeEnumObject enumobj = (SomeEnumObject)Enum.Parse(typeof(SomeEnumObject, "RANDOMENUMVAL");

Now my question is:

How do I get this enum object name that I have as a string, be written as a enum object type, dynamically since I'm trying to automate the process, becuase obviously, when I try to write:

enumArr[0] enumobj = (enumArr[0])Enum.Parse(typeof(enumArr[0], enumArr[1]);

it will throw an error because it can't parse a string as an enum.

So now, is there a way to do this without re-defining the enum?

Thanks!

Dr. Ameto
  • 95
  • 2
  • 11

1 Answers1

3

You need to use Type.GetType() or Assembly.GetType() to get the type.

You'll need to know:

  • The assembly it's in
  • The fully-qualified name (e.g. with a namespace)

If the enum is in the same assembly as the calling code, you can just use Type.GetType(fullyQualifiedName). If it's in a different assembly, you either need to create an assembly-qualified name, or find the assembly (e.g. using another type you know at compile-time) and call GetType on the assembly.

When you've parsed the enum value, the compile-time type will be object, but it really will be a (boxed) value from the enum. At that point you can:

  • Keep it as object if you don't need anything else
  • Use it dynamically with the dynamic keyword
  • Convert it back to a string using ToString() (which may not give you the same string you started with, e.g. if there are multiple names for the same value)
  • Unbox it to the underlying type. You may well know the underlying type even if you don't know the enum

You can't declare a variable using the runtime value of a variable as the type, because the compiler needs to know the type at compile-time. But one of the options above should help you.

Here's a complete example:

using System;

namespace TestApp
{
    public enum Foo
    {
        Bar = 123
    }

    public class Program
    {
        static void Main()
        {
            // You've parsed these out already
            string name = "Foo";
            string value = "Bar";

            // Work out the fully-qualified name and fetch
            // the type. We use the namespace of a type that
            // we know is in the same namespace as the enum we're
            // looking for.
            string ns = typeof(Program).Namespace;
            string fqn = $"{ns}.{name}";
            Type type = Type.GetType(fqn);
            if (type == null)
            {
                throw new Exception($"Unknown type: {fqn}");
            }

            // Parse the value
            object enumValue = Enum.Parse(type, value);
            Console.WriteLine((int) enumValue); // 123
        }
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So, basically, [Convert String to Type in C#](https://stackoverflow.com/questions/11107536/convert-string-to-type-in-c-sharp). – CodeCaster May 08 '18 at 08:56
  • @CodeCaster: With a bit more given that the aim is to then parse an enum value. I've added an extra paragraph and list about what the OP can then do with the result of parsing. – Jon Skeet May 08 '18 at 09:01
  • @DaisyShipton Thanks for the answer. That helped. Since it was a referenced assembly outside the current one, I had to use the _assembly qualified name followed by the referenced assembly's name as a string_. `Type type = Type.GetType($"{qualifiedName}, "AssemblyNameAsString");` I'm at a point where I've to work on other modules before I can get it running so don't know yet whether this will work for me but I'll let you know! Thanks again! :) – Dr. Ameto May 09 '18 at 08:27
  • @Dr.Ameto: Hope it'll work - if you already have a reference to the assembly, I personally prefer using `Assembly.GetType` instead of putting the assembly name in the string, but different use cases work better one way or the other. – Jon Skeet May 09 '18 at 08:34
  • @DaisyShipton Yes exactly, in my case, it's much easier to get the assembly name as a string. – Dr. Ameto May 09 '18 at 08:48