C# Enum Format Method


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.

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"));
   }
}

Output

Product I need is Keyboard
Product value: 1

Updated on: 23-Jun-2020

517 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements