TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Enum.Format Method

This C# example program uses the Enum.Format method. It uses the typeof operator.

Enum.Format is a standardized way to change enums to strings.

It produces hexadecimal, digit and string values from an enumerated constant. It uses format strings for this. Lowercase and uppercase make no difference.

Example. To begin, let us look at a program that uses all eight different formatting strings accepted by Enum.Format. We use a sample enum to demonstrate as well. The output shows the exact results of these formats.

The constants "G", "g", "F", and "f" all output the name of the enumerated constant as a string. The constants "X", "x", "D", and "d" output the value of the enum in hexadecimal or digit format.

C# program that demonstrates Enum.Format

using System;

class Program
{
    enum Importance
    {
	Low,
	Medium,
	Critical
    }

    static void Main()
    {
	M("G");
	M("g");
	M("X");
	M("x");
	M("F");
	M("f");
	M("D");
	M("d");
    }

    static void M(string format)
    {
	// Use Enum.Format with the specified format string.
	string value = Enum.Format(typeof(Importance), Importance.Critical, format);
	Console.WriteLine("{0} = {1}", format, value);
    }
}

Output

G = Critical
g = Critical
X = 00000002
x = 00000002
F = Critical
f = Critical
D = 2
d = 2

Usage notes. What is the use of the Enum.Format method in a real program? It provides a standardized way to produce a string that represents either the name or the value of an enum type.

Tip: You could do this by casting to the underlying type and then using ToString, but Format is another alternative.

Summary. The Enum.Format method was used to produce a string representation in a standardized format from an enumerated constant. The method provides an alternative to the ToString method and casting.

Typically: The Enum.Format method is not needed but could provide a useful bit of functionality for some programs.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf