Convert String to Enum in C#

C#

In this post, we are going to learn how to Convert String to Enum in C#.

1. C# Enum.parse() method


The enum.parse() method in the system namespace is used to convert the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Syntax

The enum.parse() overloads in .Net 4.X and 5.x.

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

#Enum.parse() generic overload in .Net 5.x
enum.Parse<TEnum> (string value)
enum.Parse<TEnum> (string value, bool ignoreCase)

Parameters :

  • enum type: It is an enumeration type.
  • value: It is string type value name or value to convert.

Return Value

  • It returns an object of enum type,if successful.
  • Important note : if the string value does not match with any of member value of enum then it will throw error.

1.1 Program to Convert String to Enum in C#


  • In this C# program,We Used Enum.GetNames() to get the all enum values alog with typeof() agrument to get type of all enum value and for each loop to iterate over enum values.
  • Enum.parse() method converting string to enum.
  • Secondly, using “(Animals)Enum.Parse(typeof(Animals), animalname,true)” to check upper case enum value “ZEBRA” by ignoring case.The boolean parameter identify if operation is case-insensitive,its True value is to ignorance case.

using System;
public class Conversion{
      enum Animals
      {
         Lion= 1,
         Tiger = 2,
         Zebra = 3
      }

    public  static void Main()
      { 
		string animalname = "ZEBRA";
		
        try
		{
        //loop through all value of enum
		foreach (string ani in Enum.GetNames(typeof(Animals)))
		 {
			 
        Animals enum_val = (Animals)Enum.Parse(typeof(Animals), ani);		
		Console.WriteLine("{0}",enum_val);	
		
        }
		
//ignorance case 	
        Animals aniname=  (Animals)Enum.Parse(typeof(Animals), animalname,true);
       
        Console.WriteLine("\n ignorance case :{0}",aniname);
        
		}
		catch (Exception ex)
         {
         Console.WriteLine("Conversion is not possible");
		}
      }
}

Output

Lion
Tiger
Zebra

1.2 Enum.parse() generic to Convert String to Enum in C#


  • In this C# program,we Used Enum.GetNames() to get the all enum values along with typeof() agrument to get type of all enum value and for each loop to iterate over enum values.
  • Enum.parse() generic in .Net 5.x method to convert string to enum.
using System;
public class Conversion{
      enum Animals
      {
         None,
         Lion= 1,
         Tiger = 2,
         Zebra = 3
      }
    public  static void Main()
      { 	
     try
	 {
		foreach (string ani in Enum.GetNames(typeof(Animals)))
		 {
		  //generic form of enum.parse() in .net 5.x
	      Animals animal1 = Enum.Parse<Animals>(ani);		
			Console.WriteLine("{0}",animal1);	
           }
		}
		catch (Exception ex)
         {
         Console.WriteLine("Conversion is not possible");
		}
      }
}

Output

Lion
Tiger
Zebra

2. C# Enum.TryParse()


The enum.TryParse() method in the system namespace is used to convert the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Syntax

enum.Parse (Type enumType, string value);
enum.Parse (Type enumType, string value, bool ignoreCase,out object output);

#Enum.tryparse() generic overload in .Net 5.x
enum.Parse<TEnum> (string value,out TEnum result )
enum.Parse<TEnum> (string value, bool ignoreCase,out TEnum output)

Return Value:

It returns true if the value is successfully converted else returns False. It does not throw exceptions. The output result saves in the out parameter.

2.1 Program to Convert String to Enum in C#


  • In this C# program Example we have Used Enum.GetNames() to get the all enum values along with typeof() agrument to get type of all enum value and for each loop to iterate over enum values.
  • enum.TryParse() method to convert string to enum

using System;
public class Conversion{
      enum animals
      {
         Lion= 1,
         Tiger = 2,
         Zebra = 3
      }
    public  static void Main()
      { 
		animals animalname; 
		  Console.WriteLine("string to enum:");
         foreach (string ani in Enum.GetNames(typeof(animals)))
		 {
			 
         if(Enum.TryParse<animals>(ani, out animalname))
		 {
         Console.WriteLine("{0}", animalname);
		 
		 }
		else
		{
			 Console.WriteLine("conversion failed");
		}
      }
      }
}

Output

string to enum:
Lion
Tiger
Zebra

3. isdefined() to Check value exist in enum


Enum.isdefined() :To check string value does exist in specified enumeration.

Syntax

IsDefined(ParameterInfo, Type, Boolean)

C# Program to Check value exist in enum

In this example, we are using the enum.isdefined() method to check value exists in enum.

using System;
public class Conversion{
      enum Animals
      {
         None,
         Lion= 1,
         Tiger = 2,
         Zebra = 3
      }
    public  static void Main()
      { 
		
        try
		{
		foreach (string ani in Enum.GetNames(typeof(Animals)))
		 {      		
        
		if(Enum.IsDefined(typeof(Animals), ani))
		 {
		    
		   Console.WriteLine("value exist:{0}",ani);         
         }
        else
		{
          Console.WriteLine("wrong animal name");
         }		
			
		}
		}
		catch (Exception ex)
         {
         Console.WriteLine("value is not exist");
		}
      }
}


Output

value exist:Lion
value exist:Tiger
value exist:Zebra

Summary

In this post, we have learned how to Convert String to Enum in C# Using some built-in methods.

  • Using C# Enum.parse() method to Convert String to Enum in C#
  • Using C# Enum.TryParse() method to Convert String to Enum in C#