C# - How to Get the Type-Code of Enum Constants?

Here, we are going to learn how to get the type-code of enum constants in C#? By Nidhi Last updated : March 29, 2023

Get the Type-Code of Enum Constants

To get the type code of enum constants, we use GetTypeCode() method.

C# program to get the type-code of enum constants

The source code to get the type-code of enum constants is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

// C# program to get the type code of enum constants.

using System;

enum COLOR {
  RED,
  GREEN,
  YELLOW,
  BLACK,
  WHITE,
  BLUE
}

class EnumDemo {
  static void PrintTypeCode(COLOR color) {
    switch (color) {
    case COLOR.RED:
      Console.WriteLine("Color is Red,    typecode: " + COLOR.RED.GetTypeCode());
      break;
    case COLOR.GREEN:
      Console.WriteLine("Color is Green,  typecode: " + COLOR.GREEN.GetTypeCode());
      break;
    case COLOR.YELLOW:
      Console.WriteLine("Color is Yellow, typecode: " + COLOR.YELLOW.GetTypeCode());
      break;
    case COLOR.BLACK:
      Console.WriteLine("Color is Black,  typecode: " + COLOR.BLACK.GetTypeCode());
      break;
    case COLOR.WHITE:
      Console.WriteLine("Color is White,  typecode: " + COLOR.WHITE.GetTypeCode());
      break;
    case COLOR.BLUE:
      Console.WriteLine("Color is Blue,   typecode: " + COLOR.BLUE.GetTypeCode());
      break;
    }
  }
 
  static void Main(string[] args) {
    PrintTypeCode(COLOR.RED);
    PrintTypeCode(COLOR.GREEN);
    PrintTypeCode(COLOR.BLUE);
  }
}

Output

Color is Red,    typecode: Int32
Color is Green,  typecode: Int32
Color is Blue,   typecode: Int32
Press any key to continue . . .

Explanation

In the above program, we created an enum COLOR that contain constants with color names. Here, we also created a class EnumDemo that contains two static methods PrintTypeCode() and Main().

In the PrintTypeCode() method, we created a switch block, here, we printed the type code of color constants based on enum constant passed into the method.

In the Main() method, we called PrintTypeCode() method with different values of COLOR enum.

C# Enum Class Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.