473,756 Members | 1,764 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 39731
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
8868
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
30163
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
4600
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
3616
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
16663
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
3351
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
2277
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
1829
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
6308
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
9455
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9869
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9838
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
9708
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7242
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
5302
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3805
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
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.