ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C# program to demonstrate the use of Parse() method of Enum class

Here, we are going to demonstrate the use of Parse() method of Enum class in C#.Net.
Submitted by Nidhi, on April 17, 2021

Here, we will learn about the Parse() method of Enum class. This 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:

  • 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:

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

Program:

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 »

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.