In one of the previous posts I have explained how we can use Enums in C#, now in this article, I have explained with an example, how to convert string to enum or enum to string in C#.
Table of Contents
String to Enum in C#
Yes, we can create strings and then convert them into Enum using Enum.Parse
method in C# to get correct Enum value of the passed string.
Let's take a look at an working example to understand it.
using System;
public class Program
{
enum BallColor
{
White=0,
Red = 1,
Green = 2
}
public static void Main()
{
string value = "Red";
// Try to convert the string to an enum.
BallColor ball = (BallColor)Enum.Parse(typeof(BallColor), value);
// Check if value matches
if (ball == BallColor.Red)
{
Console.WriteLine("Ball Color is Red");
}
}
}
Output:
Ball Color is Red
In the above example, we have created Enum as BallColor, then we have got ball color as "Red" in a string type.
Once we have string value, we try to convert it to Enum using Enum.Parse()
method, which is a static method, to use it we need to include System namespace.
Once we have Enum value, we check it, if it matches, we print message using
Console.WriteLine();
Here is the working fiddle you can run it.
If you don't want to use Enum.Parse
, we can also achieve our above goals using Enum.TryParse
, as shown below
string value = "Red";
// An uninitialized variable.
BallColor ballColor;
// Call Enum.TryParse method.
if (Enum.TryParse(value, out ballColor))
{
//yes enum type matches
Console.WriteLine(ballColor == BallColor.Red);
}
Although, above ways are great and easy to use.
If you are working with large Enums and want to have best performance, you can create a extension using Dictionary
, here is the sample code for this.
public static bool TryParse<T>(string value, out T result) where T : struct
{
var cacheKey = "Enum_" + typeof(T).FullName;
// [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.
// [Implementation off-topic.]
var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);
return enumDictionary.TryGetValue(value.Trim(), out result);
}
private static Dictionary<string, T> CreateEnumDictionary<T>()
{
return Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);
}
Enum to string in C#
Now, let's consider another scenerio in which we have Enum value and we want to get output as string.
You can simply convert Enum to string using .ToString()
which calls Enum metadata and gives the name of the Enum.
using System;
public class Program
{
enum BallColor
{
White=0,
Red = 1,
Green = 2
}
public static void Main()
{
//get enum
BallColor ballColor = BallColor.White;
string enumValue = ballColor.ToString();
//print enum to string value
Console.WriteLine(enumValue);
Console.WriteLine("using For loop");
//loop through enums using for loop
for (BallColor bc = BallColor.White; bc <= BallColor.Green; bc++)
{
string val = bc.ToString();
//print enum value using .ToString()
Console.WriteLine(val);
}
}
}
output:
White
using For loop
White
Red
Green
Using Enum.Name
Get Enum value from string using Enum.Name
, which works faster than .ToString()
method, as .ToString() calls Enum.Name internally and then show Enum value.
Syntax of Enum.Name
Enum.GetName(typeof(MyEnum), MyEnum.MyValue);
With new C# 6 or above syntax, you can use simply use:
nameof(MyEnum.MyValue)
Considering above example, if we want to convert Enum to string using Enum.GetName:
using System;
public class Program
{
enum BallColor
{
White=0,
Red = 1,
Green = 2
}
public static void Main()
{
BallColor ballColor = BallColor.White;
//get Enum value using Enum.GetName()
var val=Enum.GetName(typeof(BallColor), ballColor);
//print it
Console.WriteLine("Enum value= "+val);
}
}
Output:
Enum value= White
Helper Method to convert Enum to string and string to enum
You can simply use below helper methods, to get string or enum based on your needs.
public static String EnumToString(this Enum eff)
{
return eff.ToString();
}
public static EnumType StringToEnum<EnumType>(this String enumValue)
{
return (EnumType) Enum.Parse(typeof(EnumType), enumValue);
}
Hope it helps.
You may also like to read:
File I/O in C# (Read, Write, Delete, Copy file using C#)
Object Oriented Programming (OOPS) concepts in c# with example
Extract Text from image in C# using Tesseract