TheDeveloperBlog.com

Home | Contact Us

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

<< Back to C-SHARP

C# Enum.Format Method (typeof Enum)

Use the Enum.Format method with the typeof operator to get strings from enums.
Enum.Format. This changes 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.Enum
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.

Typeof: The typeof operator can be passed as the second argument to Enum.Format.

Typeof, nameof
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.

ToString
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.

© TheDeveloperBlog.com
The Dev Codes

Related Links:


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