C# Enum Format Method

CsharpProgrammingServer Side Programming

The Format method converts value of a specified enumerated type to its equivalent string representation. Here you can also set the format i.e. d for Decimal, x for HexaDecimal, etc.

We have the following enumeration.

enum Stock { PenDrive, Keyboard, Speakers };

The default value gets assigned (initialize).

PenDrive = 0
Keyboard = 1
Speakers = 2

Now, let’s say you want the value of “Keyboard” name.

Stock st = Stock.Keyboard;

For that, try the following and get the constant value for Keyboard name.

Enum.Format(typeof(Stock), st, "d")

The following is the entire example.


 Live Demo

using System;
class Demo {
   enum Stock { PenDrive, Keyboard, Speakers };
   static void Main() {
      Stock st = Stock.Keyboard;
      Console.WriteLine("Product I need is {0}", st);
      Console.WriteLine("Product value: {0}", Enum.Format(typeof(Stock), st, "d"));


Product I need is Keyboard
Product value: 1
Updated on 23-Jun-2020 09:11:16