none
Enum.Equals vs == RRS feed

  • Question

  • Hi, I have another newbie question. I was looking at documentation for the 'Enum.Equals()' method at the msdn2 website, Enum, and I was wondering what is the difference between using something like;

       enum Mammals { Cat, Dog, Horse, Dolphin };
       Mammals myPet = Mammals.Cat;
       Mammals yourPet = Mammals.Dog;
       if (myPet.Equals(yourPet))
       {
       }

       // and this statement
       if (myPet == yourPet)
       {
       }

    Does one method have an advantage over the other? At the msdn2 website they don't even mention "==" in the documentation. Which method is the acceptable standard and considered a best practice?

    Thanks,
    Erica
    Wednesday, February 7, 2007 6:37 PM

Answers

  • Hi,

    The signature of the enum.Equals is

    public override bool Equals (Object obj)

    So you can put any object type into it, event like this: myPet.Equals(label1) -- it returns false.

    However, if you use myPet == label1, it will pop compile error.

    And myPet.Equals(0) will return true while myPet==0 will also pop compile error. (two types beside == must be the same)

    More reference about enum type: http://msdn2.microsoft.com/en-us/library/sbbt4032.aspx

    Thank you

    Thursday, February 8, 2007 9:41 AM

All replies

  • Enum.Equals is declared as "bool Equals(object)" which means that enum value passed in would need to be boxed & unboxed.  oper== is just directly comparing the two underlying values of the enum.
    Wednesday, February 7, 2007 8:02 PM
  • Hi,

    The signature of the enum.Equals is

    public override bool Equals (Object obj)

    So you can put any object type into it, event like this: myPet.Equals(label1) -- it returns false.

    However, if you use myPet == label1, it will pop compile error.

    And myPet.Equals(0) will return true while myPet==0 will also pop compile error. (two types beside == must be the same)

    More reference about enum type: http://msdn2.microsoft.com/en-us/library/sbbt4032.aspx

    Thank you

    Thursday, February 8, 2007 9:41 AM