C# Enum Equals Method

CsharpProgrammingServer Side Programming

To find the equality between enums, use the Equals() method.

Let’s say we have the following Enum.

enum Products { HardDrive, PenDrive, Keyboard};

Create two Products objects and assign the same values.

Products prod1 = Products.HardDrive;
Products prod2 = Products.HardDrive;

Now check for equality using Equals() method. It would be True since both have the same underlying value.

Example

 Live Demo

using System;
class Program {
   enum Products {HardDrive, PenDrive, Keyboard};
   enum ProductsNew { Mouse, HeadPhone, Speakers};
   static void Main() {
      Products prod1 = Products.HardDrive;
      Products prod2 = Products.HardDrive;
      ProductsNew newProd1 = ProductsNew.HeadPhone;
      ProductsNew newProd2 = ProductsNew.Speakers;
      Console.WriteLine("Both are same products = {0}", prod1.Equals(prod2) ? "Yes" : "No");
      Console.WriteLine("Both are same products = {0}", newProd1.Equals(newProd2) ? "Yes" : "No");
   }
}

Output

Both are same products = Yes
Both are same products = No
raja
Published on 14-Sep-2018 14:42:46
Advertisements