Passing an enum as a parameter

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

    Passing an enum as a parameter

    Hi all,

    I think I've seen someone passing an emumeration in code before.

    Can anyone tell me if thats possible and why i would want to.

    Many thanks

    Kindest Regards

    Simon


  • Peter Jausovec

    #2
    Re: Passing an enum as a parameter

    Hi Simon,

    Do you mean to pass enum as a parameter to some method ?

    Let's say you have this enum:

    public enum DocumentType
    {
    invoice,
    order
    }

    and some method that has DocumentType enum as a parameter:

    public bool SaveDocument (string name, DocumentType docType)


    Maybe this isn't a very good example but sure it is possible to pass an enum
    to a method.
    --
    Regards,
    Peter Jausovec
    (http://blog.jausovec.net)
    "Simon" <sh856531@micro softs_free_emai l_service.com> je napisal v sporoèilo
    news:u6i85iI4EH A.3504@TK2MSFTN GP12.phx.gbl ...[color=blue]
    > Hi all,
    >
    > I think I've seen someone passing an emumeration in code before.
    >
    > Can anyone tell me if thats possible and why i would want to.
    >
    > Many thanks
    >
    > Kindest Regards
    >
    > Simon
    >[/color]


    Comment

    • Catherine Lowery

      #3
      Re: Passing an enum as a parameter

      Peter Jausovec wrote:
      [color=blue]
      > Hi Simon,
      >
      > Do you mean to pass enum as a parameter to some method ?
      >
      > Let's say you have this enum:
      >
      > public enum DocumentType
      > {
      > invoice,
      > order
      > }
      >
      > and some method that has DocumentType enum as a parameter:
      >
      > public bool SaveDocument (string name, DocumentType docType)
      >
      >
      > Maybe this isn't a very good example but sure it is possible to pass an enum
      > to a method.[/color]

      Unfortunately it is not possible to pass an enum to a method this way.
      Since it is a special (user-defined) value type derived from
      System.Enum, you need to pass the underlying type to the function.

      For example, to make use of the enum's members you will have to pass
      them seperately specifying their underlying type:

      private enum MyEnum : int { ONE = 1, TWO = 2, THREE = 3 }

      private void DoIt(int i)
      {
      switch (i)
      {
      case 1:
      Console.WriteLi ne("MyEnum: {0}", i);
      break;
      case 2:
      Console.WriteLi ne("MyEnum: {0}", i);
      break;
      case 3:
      Console.WriteLi ne("MyEnum: {0}", i);
      break;
      default:
      break;
      }
      }

      this.DoIt((int) MyEnum.ONE);
      this.DoIt((int) MyEnum.TWO);
      this.DoIt((int) MyEnum.THREE);

      This would print:

      MyEnum: 1
      MyEnum: 2
      MyEnum: 3

      Seems not very practical to me. Enums are simply not intended to be
      passed to functions itself rather than their members using their
      underlying type.

      Maybe someone of the MVPs is able to shed some light on enums.

      Regards

      Catherine

      Comment

      • Peter Jausovec

        #4
        Re: Passing an enum as a parameter

        Hi,

        I think that the underlying type is integer by default

        --
        Regards,
        Peter Jausovec
        (http://blog.jausovec.net)
        "Catherine Lowery" <clowery@imap.c c> je napisal v sporocilo
        news:323sqmF3hj 3cpU1@individua l.net ...[color=blue]
        > Peter Jausovec wrote:
        >[color=green]
        >> Hi Simon,
        >>
        >> Do you mean to pass enum as a parameter to some method ?
        >>
        >> Let's say you have this enum:
        >>
        >> public enum DocumentType
        >> {
        >> invoice,
        >> order
        >> }
        >>
        >> and some method that has DocumentType enum as a parameter:
        >>
        >> public bool SaveDocument (string name, DocumentType docType)
        >>
        >>
        >> Maybe this isn't a very good example but sure it is possible to pass an
        >> enum to a method.[/color]
        >
        > Unfortunately it is not possible to pass an enum to a method this way.
        > Since it is a special (user-defined) value type derived from System.Enum,
        > you need to pass the underlying type to the function.
        >
        > For example, to make use of the enum's members you will have to pass them
        > seperately specifying their underlying type:
        >
        > private enum MyEnum : int { ONE = 1, TWO = 2, THREE = 3 }
        >
        > private void DoIt(int i)
        > {
        > switch (i)
        > {
        > case 1:
        > Console.WriteLi ne("MyEnum: {0}", i);
        > break;
        > case 2:
        > Console.WriteLi ne("MyEnum: {0}", i);
        > break;
        > case 3:
        > Console.WriteLi ne("MyEnum: {0}", i);
        > break;
        > default:
        > break;
        > }
        > }
        >
        > this.DoIt((int) MyEnum.ONE);
        > this.DoIt((int) MyEnum.TWO);
        > this.DoIt((int) MyEnum.THREE);
        >
        > This would print:
        >
        > MyEnum: 1
        > MyEnum: 2
        > MyEnum: 3
        >
        > Seems not very practical to me. Enums are simply not intended to be passed
        > to functions itself rather than their members using their underlying type.
        >
        > Maybe someone of the MVPs is able to shed some light on enums.
        >
        > Regards
        >
        > Catherine[/color]


        Comment

        • Catherine Lowery

          #5
          Re: Passing an enum as a parameter

          Peter Jausovec wrote:
          [color=blue]
          > Hi,
          >
          > I think that the underlying type is integer by default
          >[/color]

          Hm, I am not sure about this, but consider the following example. It's a
          slightly different version of the previous one.

          private enum MyEnum { ONE = 1, TWO = 2, THREE = 3 }

          private void PrintMyEnum(MyE num e)
          {
          switch (e)
          {
          case MyEnum.ONE:
          Console.WriteLi ne("MyEnum: {0}", e);
          break;
          case MyEnum.TWO:
          Console.WriteLi ne("MyEnum: {0}", e);
          break;
          case MyEnum.THREE:
          Console.WriteLi ne("MyEnum: {0}", e);
          break;
          default:
          break;
          }
          }

          this.PrintMyEnu m(MyEnum.ONE);
          this.PrintMyEnu m(MyEnum.TWO);
          this.PrintMyEnu m(MyEnum.THREE) ;

          This one prints:

          MyEnum: ONE
          MyEnum: TWO
          MyEnum: THREE

          So, what's the type now?

          Regards

          Catherine

          Comment

          • Tim Jarvis

            #6
            Re: Passing an enum as a parameter

            Catherine Lowery wrote:

            [color=blue]
            > Unfortunately it is not possible to pass an enum to a method this
            > way. Since it is a special (user-defined) value type derived from
            > System.Enum, you need to pass the underlying type to the function.[/color]

            Thats simply not true, there is absolutely no problem doing this at all.

            using System;

            namespace TestProject
            {
            /// <summary>
            /// Summary description for Class1.
            /// </summary>
            public enum MusicGenre {Rock,Punk,Pop, Country,Rap,Blu es,Jazz}

            class TestClass
            {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main(string[] args)
            {
            TestClass test = new TestClass();
            test.DisplayGen re(MusicGenre.B lues);
            test.DisplayGen re(MusicGenre.C ountry);
            test.DisplayGen re(MusicGenre.J azz);
            test.DisplayGen re(MusicGenre.P op);
            test.DisplayGen re(MusicGenre.P unk);
            test.DisplayGen re(MusicGenre.R ap);
            test.DisplayGen re(MusicGenre.R ock);
            }

            public void DisplayGenre(Mu sicGenre genre)
            {
            Console.WriteLi ne(genre.ToStri ng());
            }
            }
            }

            Try that, works just fine.

            Regards Tim.

            Comment

            • Peter Jausovec

              #7
              Re: Passing an enum as a parameter

              Hi,

              Since there is no underlying type declared the Int32 is used.

              --
              Regards,
              Peter Jausovec
              (http://blog.jausovec.net)
              "Catherine Lowery" <clowery@imap.c c> je napisal v sporocilo
              news:323u5qF3he fg9U1@individua l.net ...[color=blue]
              > Peter Jausovec wrote:
              >[color=green]
              >> Hi,
              >>
              >> I think that the underlying type is integer by default
              >>[/color]
              >
              > Hm, I am not sure about this, but consider the following example. It's a
              > slightly different version of the previous one.
              >
              > private enum MyEnum { ONE = 1, TWO = 2, THREE = 3 }
              >
              > private void PrintMyEnum(MyE num e)
              > {
              > switch (e)
              > {
              > case MyEnum.ONE:
              > Console.WriteLi ne("MyEnum: {0}", e);
              > break;
              > case MyEnum.TWO:
              > Console.WriteLi ne("MyEnum: {0}", e);
              > break;
              > case MyEnum.THREE:
              > Console.WriteLi ne("MyEnum: {0}", e);
              > break;
              > default:
              > break;
              > }
              > }
              >
              > this.PrintMyEnu m(MyEnum.ONE);
              > this.PrintMyEnu m(MyEnum.TWO);
              > this.PrintMyEnu m(MyEnum.THREE) ;
              >
              > This one prints:
              >
              > MyEnum: ONE
              > MyEnum: TWO
              > MyEnum: THREE
              >
              > So, what's the type now?
              >
              > Regards
              >
              > Catherine[/color]


              Comment

              • Catherine Lowery

                #8
                Re: Passing an enum as a parameter

                Tim Jarvis wrote:
                [color=blue]
                > Catherine Lowery wrote:
                >
                >
                >[color=green]
                >>Unfortunate ly it is not possible to pass an enum to a method this
                >>way. Since it is a special (user-defined) value type derived from
                >>System.Enum , you need to pass the underlying type to the function.[/color]
                >
                >
                > Thats simply not true, there is absolutely no problem doing this at all.
                >[/color]

                [snipped sample code for brevity]

                You're right, so am I. Just as I stated previously you will need to pass
                the enum's members to make use of the values assigned to them. I posted
                a second sample to illustrate passing the enum itself. OK, I've got to
                admit that I was not very clear. What I wanted to say is, that you need
                to pass the members to make use of the value or the enum itself to make
                use of the members as constants.

                Cathetrine

                Comment

                • Catherine Lowery

                  #9
                  Re: Passing an enum as a parameter

                  Peter Jausovec wrote:
                  [color=blue]
                  > Hi,
                  >
                  > Since there is no underlying type declared the Int32 is used.
                  >[/color]

                  Thanks for the information. Just realized the same fact while testing. I
                  do not use enumerations very often since I am not very happy with the
                  concept. It's some kinda philosophical question with esotheric
                  tendencies :-)

                  Regards

                  Catherine

                  Comment

                  • Peter Jausovec

                    #10
                    Re: Passing an enum as a parameter

                    You don't need to pass the enum member to get the value assigned to them. If
                    you don't assign a value to enum member then the first member will have the
                    value 0 by default, the second member will have 1 and so on... and if you
                    set the values, well you will get the values you set :).

                    --
                    Regards,
                    Peter Jausovec
                    (http://blog.jausovec.net)
                    "Catherine Lowery" <clowery@imap.c c> je napisal v sporocilo
                    news:323vpeF3i0 u80U1@individua l.net ...[color=blue]
                    > Tim Jarvis wrote:
                    >[color=green]
                    >> Catherine Lowery wrote:
                    >>
                    >>[color=darkred]
                    >>>Unfortunatel y it is not possible to pass an enum to a method this
                    >>>way. Since it is a special (user-defined) value type derived from
                    >>>System.Enu m, you need to pass the underlying type to the function.[/color]
                    >>
                    >>
                    >> Thats simply not true, there is absolutely no problem doing this at all.
                    >>[/color]
                    >
                    > [snipped sample code for brevity]
                    >
                    > You're right, so am I. Just as I stated previously you will need to pass
                    > the enum's members to make use of the values assigned to them. I posted a
                    > second sample to illustrate passing the enum itself. OK, I've got to admit
                    > that I was not very clear. What I wanted to say is, that you need to pass
                    > the members to make use of the value or the enum itself to make use of the
                    > members as constants.
                    >
                    > Cathetrine[/color]


                    Comment

                    • Richard Blewett [DevelopMentor]

                      #11
                      Re: Passing an enum as a parameter

                      Hmmm ... bits of confusion going on in this thread ...

                      There is no problem whatsoever in passing an enum type as a paremeter and often it is a better choice than say a boolean flag. Take the RemotingConfigu ration.Register WellknownServic eType static method. Here is the signature ...

                      RemotingConfigu ration.Register WellknownServic eType( Type typeToRemote, string uri, WellKnownObject Mode mode);

                      its that last param which is the interesting one - WellKnownObject Mode is defined as follows:

                      enum WellKnownObject Mode
                      {
                      Singleton
                      SingleCall
                      }

                      so only two values. So why didn't they use a boolean as the last parameter? Because the code is much more explicit using an enum - from looking at the method call you cal see gthe activation mode of the remote objectwithout having to check the docs to see what true and false mean.

                      By defaults enums are stored as 32 bit integers but you can change this using "inheritanc e like" syntax

                      enum WellKnownObject Mode : byte
                      {
                      Singleton
                      SingleCall
                      }

                      The above says 8 bits is enough to store the value.

                      Regards

                      Richard Blewett - DevelopMentor



                      Peter Jausovec wrote:
                      [color=blue]
                      > Hi,
                      >
                      > I think that the underlying type is integer by default
                      >[/color]

                      Hm, I am not sure about this, but consider the following example. It's a
                      slightly different version of the previous one.

                      private enum MyEnum { ONE = 1, TWO = 2, THREE = 3 }

                      private void PrintMyEnum(MyE num e)
                      {
                      switch (e)
                      {
                      case MyEnum.ONE:
                      Console.WriteLi ne("MyEnum: {0}", e);
                      break;
                      case MyEnum.TWO:
                      Console.WriteLi ne("MyEnum: {0}", e);
                      break;
                      case MyEnum.THREE:
                      Console.WriteLi ne("MyEnum: {0}", e);
                      break;
                      default:
                      break;
                      }
                      }

                      this.PrintMyEnu m(MyEnum.ONE);
                      this.PrintMyEnu m(MyEnum.TWO);
                      this.PrintMyEnu m(MyEnum.THREE) ;

                      This one prints:

                      MyEnum: ONE
                      MyEnum: TWO
                      MyEnum: THREE

                      So, what's the type now?

                      Regards

                      Catherine

                      Comment

                      • Daniel O'Connell [C# MVP]

                        #12
                        Re: Passing an enum as a parameter

                        [color=blue]
                        >
                        > this.PrintMyEnu m(MyEnum.ONE);
                        > this.PrintMyEnu m(MyEnum.TWO);
                        > this.PrintMyEnu m(MyEnum.THREE) ;
                        >
                        > This one prints:
                        >
                        > MyEnum: ONE
                        > MyEnum: TWO
                        > MyEnum: THREE
                        >
                        > So, what's the type now?[/color]

                        To be clear, while the enum is backed by an integer, the type of the
                        parameter is the enum itself.

                        However, yes, without a specification Int32 is the default backing value of
                        an enum.


                        Comment

                        • Tim Jarvis

                          #13
                          Re: Passing an enum as a parameter

                          Catherine Lowery wrote:
                          [color=blue]
                          > Tim Jarvis wrote:
                          >[color=green]
                          > > Catherine Lowery wrote:
                          > >
                          > >
                          > >[color=darkred]
                          > > > Unfortunately it is not possible to pass an enum to a method this
                          > > > way. Since it is a special (user-defined) value type derived from
                          > > > System.Enum, you need to pass the underlying type to the function.[/color]
                          > >
                          > >
                          > > Thats simply not true, there is absolutely no problem doing this at
                          > > all.
                          > >[/color]
                          >
                          > [snipped sample code for brevity]
                          >
                          > You're right, so am I. Just as I stated previously you will need to
                          > pass the enum's members to make use of the values assigned to them. I
                          > posted a second sample to illustrate passing the enum itself. OK,
                          > I've got to admit that I was not very clear. What I wanted to say is,
                          > that you need to pass the members to make use of the value or the
                          > enum itself to make use of the members as constants.
                          >
                          > Cathetrine[/color]

                          I don't understand what you are saying here at all.

                          The original poster asked if he could pass an enum member as a
                          parameter to a function and Peter posted a reply and said yes and gave
                          a code example ? you then posted and said no you can't do that, and
                          this is what I don't get, How was Peters reponse wrong ? and What do
                          you mean that the underlying type of an enum needs to be passed to the
                          function ? this makes no sense to me.


                          Regards Tim.

                          Comment

                          • Glen

                            #14
                            Re: Passing an enum as a parameter

                            Hi Simon,

                            There are two situations in which I use enum types as method parameters.

                            The first is a way to consolidate multiple properties which would be
                            boolean type for a custom class object. In this case, I use the enum
                            type with the [Flags] attribute and OR the options together:

                            [Flags]
                            public enum TheOptions
                            {
                            None = 0,
                            One = 1,
                            Two = 2,
                            Three = 4,
                            Four = 8
                            }

                            static void Main(string args[])
                            {
                            // Set the options.
                            TheOptions myOptions =
                            TheOptions.One |
                            TheOptions.Thre e;

                            // Call the method with options.
                            MyMethod(myOpti ons);
                            }

                            static void MyMethod(TheOpt ions options)
                            {
                            if ((options & MyOptions.One) != 0)
                            {
                            // Option one is selected.
                            }

                            if ((options & MyOptions.Two) != 0)
                            {
                            // Option two is selected.
                            }
                            ...
                            }

                            The other condition I use enums is for a multi-state switch where a
                            boolean type is insufficient.

                            public enum GetWhat
                            {
                            None = 0,
                            This = 1,
                            That = 2,
                            TheOther = 3
                            }

                            static void Main(string[] args)
                            {
                            // Call the method.
                            ThisMethod(GetW hat.TheOther);
                            }

                            static void ThisMethod(GetW hat getWhat)
                            {
                            switch getWhat
                            {
                            case GetWhat.This:
                            // This is selected.
                            break;
                            case GetWhat.That:
                            // That is selected.
                            break;
                            case GetWhat.TheOthe r:
                            // The other is selected.
                            break;
                            }
                            }

                            For more information, look up the FlagsAttribute Class and the Value
                            Type Usage Guidelines in the MSDN documentation. The latter will give
                            you some good ideas on enum usage.

                            Hope this helps.
                            - Glen

                            Simon wrote:[color=blue]
                            > Hi all,
                            >
                            > I think I've seen someone passing an emumeration in code before.
                            >
                            > Can anyone tell me if thats possible and why i would want to.
                            >
                            > Many thanks
                            >
                            > Kindest Regards
                            >
                            > Simon
                            >
                            >[/color]

                            Comment

                            • Jeff Louie

                              #15
                              Re: Passing an enum as a parameter

                              Simon... As an example, a class factory can take an enum to specify the
                              specific concrete class that needs to be created at runtime. In response
                              to
                              user input, the selected menu handler calls on the class factory and
                              passes
                              the appropriate enum as a parameter. The class factory then returns the
                              proper concrete class at runtime in response to the specific user
                              request. The
                              concrete class methods are invoked through polymorphic method calls so
                              that the caller does not need to know the actual concrete implementation
                              at
                              runtime, only that the concrete class implements the interface or base
                              class
                              virtual method.

                              Latest news coverage, email, free stock quotes, live scores and video are just the beginning. Discover more every day at Yahoo!


                              Regards,
                              Jeff[color=blue]
                              >I think I've seen someone passing an emumeration in code before.[/color]
                              Can anyone tell me if thats possible and why i would want to.<


                              *** Sent via Developersdex http://www.developersdex.com ***
                              Don't just participate in USENET...get rewarded for it!

                              Comment

                              Working...