CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    basic questions about enum

    Hello everyone,


    I have 3 basic questions about Enum, from MSDN,

    http://msdn.microsoft.com/en-us/libr...32(VS.80).aspx

    1.

    It is mentioned "A variable of type Days can be assigned any value in the range of the underlying type;" -- I think it is not correct to say any value in the range of the underlying type, like integer, but in the range from Sat to Fri.

    For example, you can not write Days d = 65535;

    2.

    "and if additional elements have been added to the enum type, the test for default values can return true unexpectedly." I do not quite understand this scenario, could anyone show me some code please?

    3.

    "You can notice these changes when using tools such as the Console class methods, the Expression Evaluator, and so forth. (See example 3).", I have tried example 3. But what are the rules for the changes when we add System.FlagsAttribute? The document only says there will be some changes, but not clearly states what will be the changes. Any ideas?


    thanks in advance,
    George

  2. #2
    Join Date
    Oct 2003
    Location
    .NET2.0 / VS2005 Developer
    Posts
    7,104

    Re: basic questions about enum

    Quote Originally Posted by George2
    1.

    It is mentioned "A variable of type Days can be assigned any value in the range of the underlying type;" -- I think it is not correct to say any value in the range of the underlying type, like integer, but in the range from Sat to Fri.

    For example, you can not write Days d = 65535;
    Yes you can, you have to cast it, but you can write it.


    "and if additional elements have been added to the enum type, the test for default values can return true unexpectedly." I do not quite understand this scenario, could anyone show me some code please?
    When you write a switch statement, you often include a default. When working with an enum, which is a discete set of values. If you go and add more values to the enum, then there are more situations where the default case will fire


    "You can notice these changes when using tools such as the Console class methods, the Expression Evaluator, and so forth. (See example 3).", I have tried example 3. But what are the rules for the changes when we add System.FlagsAttribute? The document only says there will be some changes, but not clearly states what will be the changes. Any ideas?
    flags enums can have their values combined:

    GetChanges(DataRowState.Added | DataRowState.Modified)

    that returns rows changed or added, to a datatable. The DataRowState is a flags enum
    "it's a fax from your dog, Mr Dansworth. It looks like your cat" - Gary Larson...DW1: Data Walkthroughs 1.1...DW2: Data Walkthroughs 2.0...DDS: The DataSet Designer Surface...ANO: ADO.NET2 Orientation...DAN: Deeper ADO.NET...DNU...PQ

  3. #3
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: basic questions about enum

    Thanks cjard,


    1.

    If we write an Enum variable like d in my code, and assign it beyond the related int range from Sat to Fri, does such code have any practical usage? I think people always use the values in the range and treat the ones beyond the range as invalid values.

    2.

    I am confused. "default:" matches for all the values which does not match any values in Enum. Why "more situations where the default case will fire" if we add or remove values in Enum?

    3.

    Without the flag, we can still make OR operations on Enum values. Any specials when we use flag?

    Here is my code.

    Code:
    class Test
    {
        enum Days
        {
            Mon = 1,
            Tue = 2
        };
    
        static void Main()
        {
            int a = (int) (Days.Mon | Days.Tue);
    
            return;
        }
    }

    regards,
    George

  4. #4
    Join Date
    May 2003
    Location
    Germany
    Posts
    936

    Re: basic questions about enum

    At first, enums are very useful for the developer. It is easier to say Days.Monday than saying 1 because some developer starting the week on Monday with 1 and another on Sunday with 1. So words are easier to handle than stupid numbers.

    Let's say you have an enum of a week from monday to friday because you want to make a time sheet for your work at your company and you are writing something like this:
    Code:
    enum Days
    {
            Mon = 1,
            Tue,
            Wed,
            Thu,
            Fri
    };
    
    private string getFullDayName(Days day)
    {
      string name = String.Empty;
    
      switch(day)
      {
        case Days.Mon:
          name = "Monday";
          break;
        case Days.Tue:
          name = "Tuesday";
          break;
        case Days.Wed:
          name = "Wednesday";
          break;
        case Days.Thu:
          name = "Thursday;
          break;
        case Days.Fri:
          name = "Friday;
          break;    
        
       return name;
    }
    All works fine, but 6 months later you need to work at the weekend and you simple add these two days to the enum. What will happen? If you call the method on Saturday you will get an empty string. Not nice, isn't? Therefore it is better to use the default statement in a switch statement.

    Code:
    private string getFullDayName(Days day)
    {
      string name = String.Empty;
    
      switch(day)
      {
        case Days.Mon:
          name = "Monday";
          break;
        case Days.Tue:
          name = "Tuesday";
          break;
        case Days.Wed:
          name = "Wednesday";
          break;
        case Days.Thu:
          name = "Thursday;
          break;
        case Days.Fri:
          name = "Friday;
          break;    
        default:
          name = "This is not a working day.";
          break;
    
       return name;
    }
    And last but not least. You should not write this.
    Code:
    static void Main()
        {
            int a = (int) (Days.Mon | Days.Tue);
    
            return;
        }
    }
    Because this statement will return Wednesday and I do not believe that you want this behavior. You use flagless enums if only one value can be selected and you use flaged enums if several values can be selected at the same time.
    Useful or not? Rate my posting. Thanks.

  5. #5
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: basic questions about enum

    to your last #1 question. yes. it has practical application. enum's are used as typed constant integer or flags values. these replace some of the #define macro's in platform SDK code where what you want is an int value, but you want to limit the range that normal users would use. the other instance is when you are using an enum as a bitflag. you can combine multiple values into a single enum

    Code:
    public enum Foo { One = 1, Two = 2, Three = 4, Four = 8 }
    // ...
    Foo f = Foo.One | Foo.Three | Foo.Four
    the sum of one | three | four is 13. there is no enum member who's value is 13 (since it is a combination of multiple values).

    if you are converting input that comes to you in the form of a numeric value, and that value maps to an enum in your code, and you want to validate whether or not the value received is valid, you can test known values using Enum.IsDefined to determine that.

  6. #6
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: basic questions about enum

    Quote Originally Posted by George2
    I am confused. "default:" matches for all the values which does not match any values in Enum. Why "more situations where the default case will fire" if we add or remove values in Enum?
    For example imagine you have some existing code in a larger program. Your enumeration is having 10 items and you extend it to thirty items, because you need it in single one place of your program maybe. In all other switch statements you now have 20 additional possibilities to get default, because everytime when the value in question is one of the new values your switch statements responds with 'default' as it is other then all the values checked by the switch cases ( we have only 10 cases in all the switch statements, because as told before we only need the new values one time in the whole program, so we would and maybe also cannot change the switch cases we already have and extending them makes maybe no sense. There is nothing complicated or mystic there, think simple George.
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  7. #7
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: basic questions about enum

    Thanks torrud,


    Seems your 1st sample conflicts with what MSDN suggests to do,

    MSDN mentioned -- "and if additional elements have been added to the enum type, the test for default values can return true unexpectedly.". Seems using default is not recommended.

    You mentioned -- "Therefore it is better to use the default statement in a switch statement." Seems you suggest to use default for the situation when we need to add new values into Enum in the future.

    Any comments to clarify? :-)


    regards,
    George

  8. #8
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: basic questions about enum

    You mentioned -- "Therefore it is better to use the default statement in a switch statement." Seems you suggest to use default for the situation when we need to add new values into Enum in the future.
    I for myself as a basic standard alays using default in any swtch statement. This has shown to be very useful when you have already worked for a long time period with coding.
    This was already good in old C before C++ and enums and is still a good behaviour in today
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  9. #9
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: basic questions about enum

    Thanks MadHatte,


    My current confusion is, it seems whether or not using flags attribute has the same result. Here is my code. So, my question now is that I want to see whether there are any special usage for flags attribute which we can not have without this attribute.

    Any comments?

    Code:
    using System;
    
    class Test
    {
        enum Days
        {
            Mon = 1,
            Tue = 2
        };
    
        [Flags]
        enum DaysFlag
        {
            Mon = 1,
            Tue = 2
        };
    
        static void Main()
        {
            int a = (int) (Days.Mon | Days.Tue);
            int b = (int)(DaysFlag.Mon | DaysFlag.Tue);
    
            return;
        }
    }

    regards,
    George

  10. #10
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: basic questions about enum

    Thanks JonnyPoet,


    I am confused. Sorry my English is not very good.

    Here is my code to show my confusion.

    When we have Mon and Tue in Enum, we can have code like this,

    Code:
      switch(day)
      {
        case Days.Mon:
          name = "Monday";
          break;
        case Days.Tue:
          name = "Tuesday";
          break;
         default:
          name = "This is not a working day.";
          break;
      }
    When we have a new value in Enum, we can change code like this,

    Code:
      switch(day)
      {
        case Days.Mon:
          name = "Monday";
          break;
        case Days.Tue:
          name = "Tuesday";
          break;
        case Days.Wed:
          name = "Wednesday";
          break;
        default:
          name = "This is not a working day.";
          break;
      }
    Anything wrong? I think we can adapt code easily with using default. :-)

    Quote Originally Posted by JonnyPoet
    For example imagine you have some existing code in a larger program. Your enumeration is having 10 items and you extend it to thirty items, because you need it in single one place of your program maybe. In all other switch statements you now have 20 additional possibilities to get default, because everytime when the value in question is one of the new values your switch statements responds with 'default' as it is other then all the values checked by the switch cases ( we have only 10 cases in all the switch statements, because as told before we only need the new values one time in the whole program, so we would and maybe also cannot change the switch cases we already have and extending them makes maybe no sense. There is nothing complicated or mystic there, think simple George.

    regards,
    George

  11. #11
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: basic questions about enum

    I agree, JonnyPoet!


    But what is wrong with using default when we need to add new values in Enum -- as MSDN mentioned? I showed my code in post #10. Any comments?


    regards,
    George

  12. #12
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: basic questions about enum

    you can combine values of your enum whether or not you use a Flags attribute. the difference is in the way that value is represented:

    Code:
    enum Foo { One = 1, Two = 2, Three = 4, Four = 8 }
    [Flags]enum Bar { One = 1, Two = 2, Three = 4, Four = 8 }
    
    Foo f = (Foo)7; // value of f = 7
    Bar b = (Bar)7; // value of b = Bar.One | Bar.Two | Bar.Three

    when using a switch statement that handles various values of an int, string, or enumeration, each case statement would need to match whatever cases you need to handle. When basing your case statements on each value of an enumeration, if you include a default: case, then any enum value not specifically stated in your case statement would go to the default: case which may not be what you meant to do:

    Code:
    enum Foo { One, Two, Three, Four }
    
    //...
    Foo f = Foo.One;
    switch(f) {
        case Foo.One:
            Console.WriteLine("One");
            break;
        case Foo.Two:
            Console.WriteLine("Two");
            break;
        case Foo.Three:
            Console.WriteLine("Three");
            break;
        case Foo.Four:
            Console.WriteLine("Four");
            break;
        default:
            Console.WriteLine("Everything else...");
            break;
    }
    now the above switch statement handles every valid value of Foo. the danger is that if someone goes back and adds a Five, Six, Seven set of values to Foo, your switch statement no longer covers every valid value of Foo:

    Code:
    enum Foo { One, Two, Three, Four, Five, Six, Seven }
    
    //...
    Foo f = Foo.One;
    switch(f) {
        case Foo.One:
            Console.WriteLine("One");
            break;
        case Foo.Two:
            Console.WriteLine("Two");
            break;
        case Foo.Three:
            Console.WriteLine("Three");
            break;
        case Foo.Four:
            Console.WriteLine("Four");
            break;
        default:      // Five, Six, Seven, AND Invalid values will come here...
            Console.WriteLine("Everything else..."); 
            break;
    }



    also, answer each persons post in ONE post. reading 3 different responses on the same thread is annoying.

  13. #13
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: basic questions about enum

    Quote Originally Posted by George2
    I agree, JonnyPoet!


    But what is wrong with using default when we need to add new values in Enum -- as MSDN mentioned? I showed my code in post #10. Any comments?


    regards,
    George
    There is nothing 'wrong' with that. Don't do it such philosophic. You only have to know that it could happen and you have to decide in your programs what to do or not to do. This depends on every specific case you are working on.
    it only said:
    Quote Originally Posted by Georg2
    ...and if additional elements have been added to the enum type, the test for default values can return true unexpectedly
    You wrote this in I think it was the first post point 2. Read whats written there and dont implement deas in the concept like something is 'wrong'
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

  14. #14
    Join Date
    Mar 2007
    Posts
    59

    Re: basic questions about enum

    Here an alternative for your "switch" case problem. Instead of doing it "C++ like", why don't you use C# attributes?

    Code:
    // this class already exist, but is shown as example
    public class DisplayNameAttribute : Attribute
    {
      private string mDisplayName = null;
    
      public string DisplayName { get; set; }
    }
    
    // define your enum:
    enum Foo
    {
      [DisplayName("Foo 1")] Foo1,
      [DisplayName("Foo 2")] Foo2,
      // ...
      [DisplayName("Foo N")] FooN
    };
    
    // write some kind of helper if you want
    public static string GetDisplayName(Foo value)
    {
      // do some introspection code using FieldInfo to find the custom attribute
      // DisplayNameAttribute. If not there, just return the value name.
      return whatever;
    }
    Like that, you don't have to have the code in 2 places and there is no problem if someone add a new value, since it's always working. Other than that, MSDN is really accurate about the enum.

    Anyway, I hope you will find that post useful.

  15. #15
    George2 is offline Elite Member Power Poster
    Join Date
    Oct 2002
    Posts
    4,468

    Re: basic questions about enum

    Thanks MadHatter!


    I like your statement below. Great! One more question, besides the Console write method, any other ways we can see different representation of whether or not using flags attribute?

    Quote Originally Posted by MadHatter
    you can combine values of your enum whether or not you use a Flags attribute. the difference is in the way that value is represented:

    Thanks JonnyPoet,


    Quote Originally Posted by JonnyPoet
    it only said: You wrote this in I think it was the first post point 2. Read whats written there and dont implement deas in the concept like something is 'wrong'
    Sorry my English is not good. Do you mean cjard's reply #2? Which point do you mean in his reply?


    regards,
    George

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured