Create an enum at runtime

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lawrence Oluyede

    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
    Blogger ist ein Veröffentlichungs-Tool von Google, mit dem du ganz einfach deine Gedanken der Welt mitteilen kannst. Mit Blogger kannst du problemlos Texte, Fotos und Videos in deinem persönlichen Blog oder deinem Team-Blog veröffentlichen.

  • Lawrence Oluyede

    #2
    Re: Create an enum at runtime

    Lawrence Oluyede <raims@dot.co m> writes:
    [color=blue]
    > is there a way to do that?[/color]

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

    --
    Lawrence "Rhymes" Oluyede
    Blogger ist ein Veröffentlichungs-Tool von Google, mit dem du ganz einfach deine Gedanken der Welt mitteilen kannst. Mit Blogger kannst du problemlos Texte, Fotos und Videos in deinem persönlichen Blog oder deinem Team-Blog veröffentlichen.

    Comment

    • Lawrence Oluyede

      #3
      Problems with enum at runtime (was Re: Create an enum at runtime)


      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
      Blogger ist ein Veröffentlichungs-Tool von Google, mit dem du ganz einfach deine Gedanken der Welt mitteilen kannst. Mit Blogger kannst du problemlos Texte, Fotos und Videos in deinem persönlichen Blog oder deinem Team-Blog veröffentlichen.

      Comment

      • Richard A. Lowe

        #4
        Re: Problems with enum at runtime (was Re: Create an enum at runtime)

        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:

        "Lawrence Oluyede" <raims@dot.co m> wrote in message
        news:87d6a3bwms .fsf_-_@mobile.foo...[color=blue]
        >
        > 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[/color]
        instantiated[color=blue]
        > and FirstFoo is one of its fields... how can i do that?
        >
        >
        > --
        > Lawrence "Rhymes" Oluyede
        > http://loluyede.blogspot.com[/color]


        Comment

        • Lawrence Oluyede

          #5
          Re: Problems with enum at runtime

          "Richard A. Lowe" <chadich@yumspa myumYahoo.com> writes:
          [color=blue]
          > 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.[/color]

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

          --
          Lawrence "Rhymes" Oluyede
          Blogger ist ein Veröffentlichungs-Tool von Google, mit dem du ganz einfach deine Gedanken der Welt mitteilen kannst. Mit Blogger kannst du problemlos Texte, Fotos und Videos in deinem persönlichen Blog oder deinem Team-Blog veröffentlichen.

          Comment

          • Richard A. Lowe

            #6
            Re: Problems with enum at runtime

            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:

            "Lawrence Oluyede" <raims@dot.co m> wrote in message
            news:87r7yiptgl .fsf@mobile.foo ...[color=blue]
            > "Richard A. Lowe" <chadich@yumspa myumYahoo.com> writes:
            >[color=green]
            > > 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.[/color]
            >
            > Yes, I'm using VS.NET, but what do you mean with "generate the with a[/color]
            prebuild[color=blue]
            > event?"
            >
            > --
            > Lawrence "Rhymes" Oluyede
            > http://loluyede.blogspot.com[/color]


            Comment

            • Tom Carter

              #7
              Re: Problems with enum at runtime

              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 <raims@dot.co m> wrote in message news:<87r7yiptg l.fsf@mobile.fo o>...[color=blue]
              > "Richard A. Lowe" <chadich@yumspa myumYahoo.com> writes:
              >[color=green]
              > > 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.[/color]
              >
              > Yes, I'm using VS.NET, but what do you mean with "generate the with a prebuild
              > event?"[/color]

              Comment

              • Lawrence Oluyede

                #8
                Re: Problems with enum at runtime

                tcarternyc@hotm ail.com (Tom Carter) writes:
                [color=blue]
                > What exactly is the issue? Are you getting any error message or just
                > need some background on using enums in general?[/color]

                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
                Blogger ist ein Veröffentlichungs-Tool von Google, mit dem du ganz einfach deine Gedanken der Welt mitteilen kannst. Mit Blogger kannst du problemlos Texte, Fotos und Videos in deinem persönlichen Blog oder deinem Team-Blog veröffentlichen.

                Comment

                • Tom Carter

                  #9
                  Re: Problems with enum at runtime

                  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

                  --
                  Lawrence Oluyede <raims@dot.co m> wrote in message news:<874qve9h5 5.fsf@mobile.fo o>...[color=blue]
                  > tcarternyc@hotm ail.com (Tom Carter) writes:
                  >[color=green]
                  > > What exactly is the issue? Are you getting any error message or just
                  > > need some background on using enums in general?[/color]
                  >
                  > 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[/color]

                  Comment

                  • Lawrence Oluyede

                    #10
                    Re: Problems with enum at runtime

                    tcarternyc@hotm ail.com (Tom Carter) writes:
                    [color=blue]
                    > // 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 );
                    > }[/color]

                    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
                    Blogger ist ein Veröffentlichungs-Tool von Google, mit dem du ganz einfach deine Gedanken der Welt mitteilen kannst. Mit Blogger kannst du problemlos Texte, Fotos und Videos in deinem persönlichen Blog oder deinem Team-Blog veröffentlichen.

                    Comment

                    Working...