C# Enum Equals Method


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

Updated on: 23-Jun-2020

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements