473,387 Members | 1,420 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Create an enum at runtime


I have a list of strings and i'd like to build up an
enum from them... is there a way to do that?

Thanks in advance.

--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #1
9 39621
Lawrence Oluyede <ra***@dot.com> writes:
is there a way to do that?


I think i've found the way... i'm playing with System.Reflection.Emit

--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #2

I'm able to create an enum at runtime and fill it with the values that i
need but the problem arises when i want to use that enumeration...

....I'd like that the user of the class could do something like this:

FooClass fc = new FooClass();

fc.FooMethod(Foos.FirstFoo);

where Foos is the enumeration I build at runtime when FooClass is instantiated
and FirstFoo is one of its fields... how can i do that?
--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #3
You probably want to build the enums at compile time.. if you are using
Visual Studio you could generate them with a pre-build event. Otherwise
there's really no advantage to generating them, IMO.

Richard

--
C#, .NET and Complex Adaptive Systems:
http://blogs.geekdojo.net/Richard
"Lawrence Oluyede" <ra***@dot.com> wrote in message
news:87***************@mobile.foo...

I'm able to create an enum at runtime and fill it with the values that i
need but the problem arises when i want to use that enumeration...

...I'd like that the user of the class could do something like this:

FooClass fc = new FooClass();

fc.FooMethod(Foos.FirstFoo);

where Foos is the enumeration I build at runtime when FooClass is instantiated and FirstFoo is one of its fields... how can i do that?
--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com

Nov 15 '05 #4
"Richard A. Lowe" <ch*****@yumspamyumYahoo.com> writes:
You probably want to build the enums at compile time.. if you are using
Visual Studio you could generate them with a pre-build event. Otherwise
there's really no advantage to generating them, IMO.


Yes, I'm using VS.NET, but what do you mean with "generate the with a prebuild
event?"

--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #5
You can run an executable before VS.NET builds your code - it's under the
project properties-->Common Properties-->Build Events. You would have to
develop the app that generated your enum, of course, but you could easily
run it by entering it's command line as the Pre-build event.

R.

--
C#, .NET and Complex Adaptive Systems:
http://blogs.geekdojo.net/Richard
"Lawrence Oluyede" <ra***@dot.com> wrote in message
news:87************@mobile.foo...
"Richard A. Lowe" <ch*****@yumspamyumYahoo.com> writes:
You probably want to build the enums at compile time.. if you are using
Visual Studio you could generate them with a pre-build event. Otherwise
there's really no advantage to generating them, IMO.
Yes, I'm using VS.NET, but what do you mean with "generate the with a

prebuild event?"

--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com

Nov 15 '05 #6
Hi Lawrence,

What exactly is the issue? Are you getting any error message or just
need some background on using enums in general?

If the latter please review the following example which is pulled
directly from msdn (http://msdn.microsoft.com/library/de...pspec_14_3.asp)

using System;
enum Color
{
Red,
Green = 10,
Blue
}
class Test
{
static void Main() {
Console.WriteLine(StringFromColor(Color.Red));
Console.WriteLine(StringFromColor(Color.Green));
Console.WriteLine(StringFromColor(Color.Blue));
}
static string StringFromColor(Color c) {
switch (c) {
case Color.Red:
return String.Format("Red = {0}", (int) c);
case Color.Green:
return String.Format("Green = {0}", (int) c);
case Color.Blue:
return String.Format("Blue = {0}", (int) c);
default:
return "Invalid color";
}
}
}
~~~~~~~~~~~~~
Tommie Carter
--
If the latter just check out
Lawrence Oluyede <ra***@dot.com> wrote in message news:<87************@mobile.foo>...
"Richard A. Lowe" <ch*****@yumspamyumYahoo.com> writes:
You probably want to build the enums at compile time.. if you are using
Visual Studio you could generate them with a pre-build event. Otherwise
there's really no advantage to generating them, IMO.


Yes, I'm using VS.NET, but what do you mean with "generate the with a prebuild
event?"

Nov 15 '05 #7
tc********@hotmail.com (Tom Carter) writes:
What exactly is the issue? Are you getting any error message or just
need some background on using enums in general?


No :) I think that I'm able to use enums but I'm not able to create them
at runtime... here's some code to explain what i mean:

AppDomain domain = Thread.GetDomain();
AssemblyName name = new AssemblyName();
name.Name = "EnumAssembly";
AssemblyBuilder asmBuilder = domain.DefineDynamicAssembly(
name, AssemblyBuilderAccess.Run);
ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("EnumModule");
EnumBuilder enumBuilder = modBuilder.DefineEnum("Language",
TypeAttributes.Public,
typeof(System.Int32));

for(int i = 0; i < al.Count; i++)
// here al is an array list with a list of string values
enumBuilder.DefineLiteral(al[i].ToString(), i);

Type enumType = enumBuilder.CreateType();

Enum enumObj = (Enum) Activator.CreateInstance(enumType);

// here is an example
enumType.GetField("ar-SA").SetValue(enumObj, 1);
What I'd like to is that when a dev use the class containing such code
could use enumObj like a normal enum AA { a, b, c }

Bye
--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #8
Hi Lawrence,

I have taken some time to put together the example so that I could
gain a better understanding of what you are attempting to do -- so
here is what I saw (hope it matches your intent).

using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
namespace EnumTest1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
AppDomain domain = Thread.GetDomain();
AssemblyName name = new AssemblyName();
name.Name = "EnumAssembly";
AssemblyBuilder asmBuilder = domain.DefineDynamicAssembly(
name, AssemblyBuilderAccess.Run);
ModuleBuilder modBuilder =
asmBuilder.DefineDynamicModule("EnumModule");
EnumBuilder enumBuilder = modBuilder.DefineEnum("Language",
TypeAttributes.Public,
typeof(System.Int32));
string[] al={"en-US","en-UK","ar-SA","da-DK","French","Cantonese"};
for(int i = 0; i < al.Length; i++)
{
// here al is an array list with a list of string values
enumBuilder.DefineLiteral(al[i].ToString(), i);
}
Type enumType = enumBuilder.CreateType();
Enum enumObj = (Enum) Activator.CreateInstance(enumType);
// here is an example
try
{
enumType.GetField("en-US").SetValue(enumObj, 1);
}
catch( Exception e )
{
// Any exception generated is displayed.
Console.WriteLine( "Exception: {0}", e.Message );
}
}
}
}
The only error I get is when we try to set the field value using the
enumObj (which is just an instance of the enum struct with the default
enum only)

The error is:

"Cannot set a final field"

I guess I'm not sure that you can set an enum in the same manner
as you'd set a field value (at least within the context of using this
function).

I see no reason why a developer could not legitimately use the
enums defined in the module that you created...

An alternative to trying to set the field of the object might be
to pass data between application domains using the SetData and GetData
methods of the AppDomain class (to pass the values for the Language
enum).

Good Luck,
~~~~~~~~~~~~~
Tommie Carter
www.premiertechnology.com
--
Lawrence Oluyede <ra***@dot.com> wrote in message news:<87************@mobile.foo>...
tc********@hotmail.com (Tom Carter) writes:
What exactly is the issue? Are you getting any error message or just
need some background on using enums in general?


No :) I think that I'm able to use enums but I'm not able to create them
at runtime... here's some code to explain what i mean:

AppDomain domain = Thread.GetDomain();
AssemblyName name = new AssemblyName();
name.Name = "EnumAssembly";
AssemblyBuilder asmBuilder = domain.DefineDynamicAssembly(
name, AssemblyBuilderAccess.Run);
ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("EnumModule");
EnumBuilder enumBuilder = modBuilder.DefineEnum("Language",
TypeAttributes.Public,
typeof(System.Int32));

for(int i = 0; i < al.Count; i++)
// here al is an array list with a list of string values
enumBuilder.DefineLiteral(al[i].ToString(), i);

Type enumType = enumBuilder.CreateType();

Enum enumObj = (Enum) Activator.CreateInstance(enumType);

// here is an example
enumType.GetField("ar-SA").SetValue(enumObj, 1);
What I'd like to is that when a dev use the class containing such code
could use enumObj like a normal enum AA { a, b, c }

Bye

Nov 15 '05 #9
tc********@hotmail.com (Tom Carter) writes:
// here is an example
try
{
enumType.GetField("en-US").SetValue(enumObj, 1);
}
catch( Exception e )
{
// Any exception generated is displayed.
Console.WriteLine( "Exception: {0}", e.Message );
}


Thanks Tom, I think you've understood but my question still remains
up there... enumType.GetField("en-US").SetBlablah is not a wonderful
way to use an enum. What i want to know if it could be done is:
can I use enumObj like a standard compile time enum (I mean typing
enumObj.en-US)?

Thanks for your help Tom.

--
Lawrence "Rhymes" Oluyede
http://loluyede.blogspot.com
Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I...
2
by: Dennis C. Drumm | last post by:
This is a restatement of an earlier post that evidently wasn't clear. I am building a custom MessageBox dialog that has, among other things, a few new button options (yes to all, no to all, etc.)...
21
by: Andreas Huber | last post by:
Hi there Spending half an hour searching through the archive I haven't found a rationale for the following behavior. using System; // note the missing Flags attribute enum Color {
31
by: Michael C | last post by:
If a class inherits from another class, say Form inherits from control, then I can assign the Form to a variable of type Control without needing an explicit conversion, eg Form1 f = new Form1();...
15
by: apm | last post by:
Can an enum start empty and be added to on the fly?
2
by: Steve Teeples | last post by:
How does one go about creating an enum at runtime from an array of strings? -- Steve
12
by: Laurent Deniau | last post by:
If I understand well, an enumeration is only garantee to hold at most an int (6.7.2.2-2). So I would like to know: how to store a long in an enum? enum { p2_31 = 1L << 31 }; // boom how to...
6
by: Marc Robitaille | last post by:
Hello, Is it possible to add a property to a class on the fly? If yes, How can I do this or where can I find an exemple? Thank you Marc R.
1
by: shapper | last post by:
Hello, I have an enumeration, A, with 10 items. I want to create a second enum, B, at runtime having 5 of the items of enum A. Is this possible? Thanks,
3
by: John Wright | last post by:
I have an enum based on a lookup table in my database. However, when a new item is added to the lookup table or one is removed, I have to modify the enum to match. Is there a way to dynamically...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.