CSharp - Enum to String convert and Parse

Introduction

To convert an enum to a string, either call the static Enum.Format method or call ToString on the instance.

Each method accepts a format string:

Flag Meaning
"G"for default formatting behavior,
"D" emit the underlying integral value as a string,
"X" for the same in hexadecimal,
"F"to format combined members of an enum without the Flags attribute.

Enum.Parse converts a string to an enum.

It accepts the enum type and a string that can include multiple members:

[Flags] public enum Directions {
   Left=1, Right=2, Top=4, Bottom=8
}

Directions leftRight = (Directions) Enum.Parse (typeof (Directions),"Left, Right");

An optional third argument lets you perform case-insensitive parsing.

An Argument Exception is thrown if the member is not found.

Demo

using System;

[Flags] public enum Directions {
   Left=1, Right=2, Top=4, Bottom=8//w w w.  ja  va 2  s.c o m
}


class MainClass
{
   public static void Main(string[] args)
   {
        string s = Directions.Top.ToString("G");
        Console.WriteLine(s);
        Directions leftRight = (Directions) Enum.Parse (typeof (Directions),"Left, Right");
        Console.WriteLine(leftRight);
   }
}

Result

Related Topic