C# Enum CompareTo Method

CsharpProgrammingServer Side Programming

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


 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 );


Stock for Keyboard is more than PenDrive?
Published on 14-Sep-2018 14:41:21