C# Enum ToString(String)

Description

Enum ToString(String) converts the value of this instance to its equivalent string representation using the specified format.

Syntax

Enum.ToString(String) has the following syntax.


public string ToString(
  string format
)

Parameters

Enum.ToString(String) has the following parameters.

  • format - A format string.

Returns

Enum.ToString(String) method returns The string representation of the value of this instance as specified by format.

Example

The following example demonstrates how to convert an enumerated value to a string.


//  w w  w .ja v a  2  s . co  m

using System;

class Sample 
{
    enum Colors {Red, Green, Blue, Yellow = 12};

    public static void Main() 
    {
    Colors myColor = Colors.Yellow;

    Console.WriteLine("Colors.Red = {0}", Colors.Red.ToString("d"));
    Console.WriteLine("Colors.Green = {0}", Colors.Green.ToString("d"));
    Console.WriteLine("Colors.Blue = {0}", Colors.Blue.ToString("d"));
    Console.WriteLine("Colors.Yellow = {0}", Colors.Yellow.ToString("d"));

    Console.WriteLine("{0}myColor = Colors.Yellow{0}", Environment.NewLine);

    Console.WriteLine("myColor.ToString(g) = {0}", myColor.ToString("g"));
    Console.WriteLine("myColor.ToString(G) = {0}", myColor.ToString("G"));

    Console.WriteLine("myColor.ToString(x) = {0}", myColor.ToString("x"));
    Console.WriteLine("myColor.ToString(X) = {0}", myColor.ToString("X"));

    Console.WriteLine("myColor.ToString(d) = {0}", myColor.ToString("d"));
    Console.WriteLine("myColor.ToString(D) = {0}", myColor.ToString("D"));    

    Console.WriteLine("myColor.ToString(f) = {0}", myColor.ToString("f"));
    Console.WriteLine("myColor.ToString(F) = {0}", myColor.ToString("F"));
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version