Open In App

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

Enum.Format(Type, Object, String) Method is used to convert the specified value of a specified enumerated type to its equivalent string representation according to the specified format.

Syntax:



public static string Format (Type enumType, object value, string format);

Parameters:

Returns: This method returns the string representation of value.



Exceptions:

Below programs illustrate the use of the above-discussed method.

Example 1:




// C# program to illustrate the
// Enum.Format(Type, Object,
// String) Method
using System;
  
enum Animals { Dog,
               Cat,
               Cow };
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        Animals fav = Animals.Cat;
  
        Console.WriteLine("My favorite Animal is {0}.", fav);
  
        // using the Method and here
        // "d" specify the value in
        // decimal form.
        Console.WriteLine("The value of my favorite Animal is {0}.",
                          Enum.Format(typeof(Animals), fav, "d"));
  
        // using the Method and here
        // "x" specify the value in
        // hexadecimal form.
        Console.WriteLine("The hex value of my Animal  is {0}.",
                          Enum.Format(typeof(Animals), fav, "x"));
    }
}

Output:
My favorite Animal is Cat.
The value of my favorite Animal is 1.
The hex value of my Animal  is 00000001.

Example 2:




// C# program to illustrate the
// Enum.Format(Type, Object,
// String) Method
using System;
  
enum Animals { Dog,
               Cat,
               Cow };
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        Animals fav = Animals.Cat;
  
        Console.WriteLine("My favorite Animal is {0}.", fav);
  
        // using the Method and format is null
        // thats why it give exception
        Console.WriteLine("The value of my favorite Animal is {0}.",
                          Enum.Format(typeof(Animals), fav, null));
    }
}

Runtime Error:

Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: format

Note: Below are some valid values for the format parameter.

Reference:


Article Tags :
C#