473,671 Members | 2,403 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 39694
Lawrence Oluyede <ra***@dot.co m> writes:
is there a way to do that?


I think i've found the way... i'm playing with System.Reflecti on.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(Fo os.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.co m> 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(Fo os.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*****@yumspa myumYahoo.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.co m> wrote in message
news:87******** ****@mobile.foo ...
"Richard A. Lowe" <ch*****@yumspa myumYahoo.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.WriteLi ne(StringFromCo lor(Color.Red)) ;
Console.WriteLi ne(StringFromCo lor(Color.Green ));
Console.WriteLi ne(StringFromCo lor(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.co m> wrote in message news:<87******* *****@mobile.fo o>...
"Richard A. Lowe" <ch*****@yumspa myumYahoo.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********@hotm ail.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.GetDomai n();
AssemblyName name = new AssemblyName();
name.Name = "EnumAssemb ly";
AssemblyBuilder asmBuilder = domain.DefineDy namicAssembly(
name, AssemblyBuilder Access.Run);
ModuleBuilder modBuilder = asmBuilder.Defi neDynamicModule ("EnumModule ");
EnumBuilder enumBuilder = modBuilder.Defi neEnum("Languag e",
TypeAttributes. Public,
typeof(System.I nt32));

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

Type enumType = enumBuilder.Cre ateType();

Enum enumObj = (Enum) Activator.Creat eInstance(enumT ype);

// here is an example
enumType.GetFie ld("ar-SA").SetValue(e numObj, 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.Threadin g;
using System.Reflecti on;
using System.Reflecti on.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.GetDomai n();
AssemblyName name = new AssemblyName();
name.Name = "EnumAssemb ly";
AssemblyBuilder asmBuilder = domain.DefineDy namicAssembly(
name, AssemblyBuilder Access.Run);
ModuleBuilder modBuilder =
asmBuilder.Defi neDynamicModule ("EnumModule ");
EnumBuilder enumBuilder = modBuilder.Defi neEnum("Languag e",
TypeAttributes. Public,
typeof(System.I nt32));
string[] al={"en-US","en-UK","ar-SA","da-DK","French","C antonese"};
for(int i = 0; i < al.Length; i++)
{
// here al is an array list with a list of string values
enumBuilder.Def ineLiteral(al[i].ToString(), i);
}
Type enumType = enumBuilder.Cre ateType();
Enum enumObj = (Enum) Activator.Creat eInstance(enumT ype);
// here is an example
try
{
enumType.GetFie ld("en-US").SetValue(e numObj, 1);
}
catch( Exception e )
{
// Any exception generated is displayed.
Console.WriteLi ne( "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.co m> wrote in message news:<87******* *****@mobile.fo o>...
tc********@hotm ail.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.GetDomai n();
AssemblyName name = new AssemblyName();
name.Name = "EnumAssemb ly";
AssemblyBuilder asmBuilder = domain.DefineDy namicAssembly(
name, AssemblyBuilder Access.Run);
ModuleBuilder modBuilder = asmBuilder.Defi neDynamicModule ("EnumModule ");
EnumBuilder enumBuilder = modBuilder.Defi neEnum("Languag e",
TypeAttributes. Public,
typeof(System.I nt32));

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

Type enumType = enumBuilder.Cre ateType();

Enum enumObj = (Enum) Activator.Creat eInstance(enumT ype);

// here is an example
enumType.GetFie ld("ar-SA").SetValue(e numObj, 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********@hotm ail.com (Tom Carter) writes:
// here is an example
try
{
enumType.GetFie ld("en-US").SetValue(e numObj, 1);
}
catch( Exception e )
{
// Any exception generated is displayed.
Console.WriteLi ne( "Exception: {0}", e.Message );
}


Thanks Tom, I think you've understood but my question still remains
up there... enumType.GetFie ld("en-US").SetBlabl ah 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
8853
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 want my users to be able to select a report, click on a command button on a form, which will then automatically create the report as a pdf file and save it to the user's machine. I am using Adobe Acrobat (5.0 I think) and have Adobe Distiller as a
2
30143
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.) and would like to make the dialog look and act like the standard MessageBox. Therefore, I would like to put in the message section the same type of icons found in the MessageBox dialog, such as MessageBoxIcon.Exclamation. In another post here I had...
21
4588
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
3590
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(); Control c = f; An enum value inherits from int but it doesn't get implicitly converted: HorizontalAlignment h = HorizontalAlignment.Center;
15
16652
by: apm | last post by:
Can an enum start empty and be added to on the fly?
2
830
by: Steve Teeples | last post by:
How does one go about creating an enum at runtime from an array of strings? -- Steve
12
3343
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 define a synonym of a constant address?
6
2272
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
1824
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
6302
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 load the enum when the class is instantiated? I was thinking a stored procedure to load it but can't figure out how to do this. John
0
8397
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8919
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8599
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7439
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6230
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5696
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4409
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2813
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2052
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.