Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an enum value from an assembly using late binding in C#

Tags:

c#

reflection

I have a C# 3.0 WinForms application which is occasionally required to control Excel with automation. This is working nicely with normal early binding but I've had some problems when people don't have Excel installed but still want to use my app except for the Excel part. Late binding seems to be a solution to this. Late binding is rather tedious in C# 3 but I'm not doing anything particularly difficult. I'm following http://support.microsoft.com/kb/302902 as a starter and it's working out well.

My question is how can I use an enum by name?

e.g, how can I use reflection to get the value of Microsoft.Office.Interop.Excel.XlFileFormat.xlTextWindows so that I can use it an InvokeMethod call?

I know the easiest way is probably to create my own local enum with the same "magic" integer value but it would be nicer to be able to access it by name. The docs often don't list the value so to get it I probably need to have a little early bound test app that can tell me the value.

Thanks

like image 941
tetranz Avatar asked Jun 17 '10 20:06

tetranz


People also ask

What is unscoped enum type?

In an unscoped enum, the scope is the surrounding scope; in a scoped enum, the scope is the enum-list itself. In a scoped enum, the list may be empty, which in effect defines a new integral type. By using this keyword in the declaration, you specify the enum is scoped, and an identifier must be provided.

How is enum stored in memory?

enums are not allocated in memory - they exist only on compilation stage. They only exist to tell compiler what value is Tuesday in ur example. When code runs - there is no enums there anymore.

Can enums hold strings?

No they cannot. They are limited to numeric values of the underlying enum type.

Is enum a class In c#?

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).


1 Answers

The enum values are considered fields so you can use the method Type.GetField to obtain the value of an enumeration option through reflection.

A condensed example:

namespace ConsoleApp
{
    enum Foo { Bar = 5 }

    class Program
    {
        static void Main()
        {
            // Get the assembly containing the enum - Here it's the one executing
            var assembly = Assembly.GetExecutingAssembly();

            // Get the enum type
            var enumType = assembly.GetType("ConsoleApp.Foo");

            // Get the enum value
            var enumBarValue = enumType.GetField("Bar").GetValue(null);

            // Use the enum value
            Console.WriteLine("{0}|{1}", enumBarValue, (int)enumBarValue);
        }
    }
}

Outputs:

// Bar|5
like image 54
João Angelo Avatar answered Sep 23 '22 10:09

João Angelo