Comparing enum members in C#

CsharpProgrammingServer Side Programming

To compare enum members, use the Enum.CompareTo() method.

Firstly, set the values for students.

enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };

Now use the compareTo() method to compare one enum value with another.

Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );

The following is the code to compare enum members in C#.

Example

 Live Demo

using System;
public class Demo {
   enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };
   public static void Main() {
      StudentRank student1 = StudentRank.Tom;
      StudentRank student2 = StudentRank.Henry;
      StudentRank student3 = StudentRank.Amit;
      Console.WriteLine("{0} has more rank than {1}?", student1, student2);
      Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );
   }
}

Output

Tom has more rank than Henry?
Yes
raja
Published on 17-Sep-2018 13:02:25
Advertisements