c sharp

C# IsEnum Property

Enum (Enumeration) in C# is a keyword that is used to create User defined values. In an Enum, we can store multiple values at a time. Sometimes, we have to check whether the given Type is Enum or not. Type class in C# provide us a property called IsEnum that checks if the Type is Enum or not.

Creation:

enum name
{
   // User defined values separated by comma.
}


IsEnum Property

The IsEnum property from the Type class checks if the specified Type is Enum or not. If it is Enum, True is returned. Otherwise, False is returned.

Syntax:

typeof(Type).IsEnum

Return Type:

It returns the Boolean value (True/False).

Example 1:

Let’s create an Enum class with three values and check if it is Enum or not.

using System;
class Linuxhint
{
    //create enum named Food with 3 values
  enum Food
{
    Chocos,Veg,Chips
}
    static public  void Main(){
   
    //check the Food is enum or not
Console.WriteLine("Is Food Enum Type ?: "+ typeof(Food).IsEnum);
Console.WriteLine("Is Food Enum Type ?: "+ typeof(Linuxhint).IsEnum);
}
}

Output:

Explanation:

Line 4-8:

Enum creation:

Explanation:

Line 11-14:

Check if Food and Linuxhint are Enum or not.

Food is Enum hence it returned True. Linuxhint is a class which is not Enum, so False is returned.

Example 2:

Let’s create an interface and Abstract class and check if they are Enum or not.
using System:

//create interface
         interface Food{
             //this is interface
         }
         
//create abstract class
         abstract class Data{
             //this is abstract c;ass
         }
class Linuxhint
{
   
    static public  void Main(){
       
   
 //check the Food interface is enum or not
Console.WriteLine("Is Food Enum Type ?: "+ typeof(Food).IsEnum);

//check the Data abstract class is enum or not
Console.WriteLine("Is Data Enum Type ?: "+ typeof(Data).IsEnum);

}
}

Output:

Explanation:

Line 3 to 11:

We created an interface named Food and an abstract class named Data.

Line 18 to 22:

Let’s check if these are Enum or not.

They are not Enum so for both of them False is returned.

Conclusion

In this C# tutorial, we saw how to check if the Type is Enum or not using the IsEnum property. This property tells us by returning a Boolean value with two examples. If it is True, we can say that the Type is Enum and If it is False, we can say that the type is not an Enum.

Happy Coding

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain