Converting Enumerated type to String according to the Specified Format in C#


Enumerations (enums) are a powerful feature in C# that allows you to define a type with a set of named constants. Often, you may need to convert an enum value to a string for display purposes or to process it further. This article will guide you through the process of converting an enumerated type to a string according to a specified format in C#.

Understanding Enumerated Types in C#

Before proceeding with the conversion process, let's first understand what enumerated types are. An enumerated type, or enum, is a distinct type that consists of a set of named constants. Here's an example of an enumerated type in C# −

public enum Days {
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday,
   Sunday
}

In this example, Days is an enumerated type that represents the days of the week.

Converting Enumerated Type to String

In C#, it's straightforward to convert an enumerated type to a string. We can use the ToString method, which is available for all types in C#.

Example

Here's an example −

using System;

enum Days {
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday,
   Sunday
}

class Program {
   static void Main() {
      Days today = Days.Friday;
      string todayAsString = today.ToString();

      Console.WriteLine(todayAsString);  // Outputs: Friday
   }
}

In this example, we first define an enum variable today with the value Days.Friday. We then call the ToString method on today to convert it to a string. The result is assigned to todayAsString.

Output

Friday

Specifying a Format for the Conversion

While using ToString, you can also specify a format for the conversion. The format "G" is for general (the default), "D" is for decimal, "X" is for hexadecimal, and "F" is for flags.

Example

Here's an example of specifying a format −

using System;

enum Days {
   Sunday = 0,
   Monday = 1,
   Tuesday = 2,
   Wednesday = 3,
   Thursday = 4,
   Friday = 5,
   Saturday = 6
}

class Program {
   static void Main() {
      Days today = Days.Friday;
      string todayAsString = today.ToString("D");

      Console.WriteLine(todayAsString);  // Outputs: 5
   }
}

In this example, we use the "D" format, which converts the enum to its decimal equivalent. Since Days.Friday is the fifth value in the Days enumeration, and enumeration indexing starts from 0, it's represented as 4 in decimal format.

Output

5

Conclusion

Converting an enumerated type to a string in C# is a straightforward process, made even more flexible by the ability to specify a format for the conversion. Understanding this conversion is essential as it allows you to display or process enum values in a way that suits your specific needs.

Updated on: 24-Jul-2023

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements