C# Enum CompareTo Method


Compare two enums using the CompareTo() method in C#.

The method returns any of the following value −

  • Less than zero: Value of source is less than value of target
  • Zero: Value of source is equal to the value of target
  • More than zero: Value of source is more than value of target

Example

 Live Demo

using System;
class Program {
   enum Products { HardDrive = 0, PenDrive = 4, Keyboard = 8 };
   static void Main() {
      Products prod1 = Products.HardDrive;
      Products prod2 = Products.PenDrive;
      Products prod3 = Products.Keyboard;
      Console.WriteLine("Stock for {0} is more than {1}?", prod3, prod2);
      Console.WriteLine( "{0}{1}",prod3.CompareTo(prod2) > 0 ? "Yes" : "No", Environment.NewLine );
   }
}

Output

Stock for Keyboard is more than PenDrive?
Yes

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements