C# - Enum.Parse() Method with Example

In this tutorial, we will learn about the C# Enum.Parse() method with its definition, usage, syntax, and example. By Nidhi Last updated : March 29, 2023

C# Enum.Parse() Method

The Enum.Parse() method is used to convert the string representation of the name or numeric value of the one or more enumerated constant to an equivalent enumerated object. This is two times overloaded method.

Syntax

object Enum.Parse(Type enumType, string value);
object Enum.Parse(Type enumType, string value, bool ignoreCase);

Parameter(s)

  • enumType: Type of enum object.
  • value: String value to be parsed.
  • ignoreCase: It specifies operation whether an operation is case sensitive or not.

Return Value

This method returns parsed objects on the basis of passed values.

Exception(s)

  • System.OverflowExcetion
  • System.ArgumentException
  • System.ArgumentNullException

C# Example of Enum.Parse() Method

The source code to demonstrate the use of Parse() method of Enum class is given below. The given program is compiled and executed successfully.

using System;

class Sample {
  enum Directions {
    EAST = 0, WEST = 1, NORTH = 2, SOUTH = 3
  };

  //Entry point of Program
  static public void Main() {
    Directions dir;

    //Parse string to objects then 
    //we convert it to Enum objects
    dir = (Directions) Enum.Parse(typeof (Directions), "1");
    Console.WriteLine(Enum.GetName(typeof (Directions), dir));

    //Parse string to objects then 
    //we convert it to Enum objects with ignore case
    dir = (Directions) Enum.Parse(typeof (Directions), "3", true);
    Console.WriteLine(Enum.GetName(typeof (Directions), dir));
  }
}

Output

WEST
SOUTH
Press any key to continue . . .

C# Enum Class Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.