How to compare an enum value and a string that should match the enum name in C#

1 Answer

0 votes
using System;

class Program
{
    enum EN
    {
        A = 0,
        B = 1,
        C = 2
    }

    public static void Main()
    {
        // Checks if the name of EN.C is "C".
        Console.WriteLine(Enum.GetName(typeof(EN), EN.C) == "C");
        
        // Converts EN.C to string and compares it to "C".
        Console.WriteLine(EN.C.ToString() == "C");
        
        // Parses the string "C" into the enum and checks if it equals EN.C.
        Console.WriteLine((EN)Enum.Parse(typeof(EN), "C") == EN.C);
    }
}


 
/*
run:
 
True
True
True

*/

 



answered Aug 1, 2025 by avibootz
...