Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Enum to String

Tags:

.net

enums

People also ask

Can enum be converted to string Java?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

How do you convert an enum type to a specified string format?

The following example demonstrates converting an enumerated value to a string. type Colors = | Red = 1 | Blue = 2 let myColors = Colors. Red printfn $"The value of this instance is '{myColors. ToString()}'" // Output. // The value of this instance is 'Red'.

Can we convert enum to string C++?

The stringify() macro method is used to convert an enum into a string. Variable dereferencing and macro replacements are not necessary with this method. The important thing is that, only the text included in parenthesis may be converted using the stringify() method.

Can we convert string to enum in C#?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.


As of C#6 the best way to get the name of an enum is the new nameof operator:

nameof(MyEnum.EnumValue);

// Ouputs
> "EnumValue"

This works at compile time, with the enum being replaced by the string in the compiled result, which in turn means this is the fastest way possible.

Any use of enum names does interfere with code obfuscation, if you consider obfuscation of enum names to be worthwhile or important - that's probably a whole other question.


Works for our project...

public static String convertToString(this Enum eff)
{
    return Enum.GetName(eff.GetType(), eff);
}

public static EnumType converToEnum<EnumType>(this String enumValue)  
{
    return (EnumType) Enum.Parse(typeof(EnumType), enumValue);
}

In my tests, Enum.GetName was faster and by decent margin. Internally ToString calls Enum.GetName. From source for .NET 4.0, the essentials:

public override String ToString()
{
     return Enum.InternalFormat((RuntimeType)GetType(), GetValue());
}

private static String InternalFormat(RuntimeType eT, Object value)
{
    if (!eT.IsDefined(typeof(System.FlagsAttribute), false))
    {
        String retval = GetName(eT, value); //<== the one
        if (retval == null)
            return value.ToString();
        else
            return retval;
    }
    else
    {
        return InternalFlagsFormat(eT, value);
    }
}

I cant say that is the reason for sure, but tests state one is faster than the other. Both the calls involve boxing (in fact they are reflection calls, you're essentially retrieving field names) and can be slow for your liking.

Test setup: enum with 8 values, no. of iterations = 1000000

Result: Enum.GetName => 700 ms, ToString => 2000 ms

If speed isn't noticeable, I wouldn't care and use ToString since it offers a much cleaner call. Contrast

Enum.GetName(typeof(Bla), value)

with

value.ToString()

Enum.GetName(...)

This is the most elegant method that is meant for it.

var enumValueString = Enum.GetName(typeof (MyEnum), MyEnum.MyValue);

Although I don't see any issues with calling .ToString() as it is simply shorter.

var enumValueString = MyEnum.MyValue.ToString();

With new C# 6 syntax you can use:

nameof(MyEnum.MyValue)

All of these internally end up calling a method called InternalGetValueAsString. The difference between ToString and GetName would be that GetName has to verify a few things first:

  1. The type you entered isn't null.
  2. The type you entered is, in fact an enumeration.
  3. The value you passed in isn't null.
  4. The value you passed in is of a type that an enumeration can actually use as it's underlying type, or of the type of the enumeration itself. It uses GetType on the value to check this.

.ToString doesn't have to worry about any of these above issues, because it is called on an instance of the class itself, and not on a passed in version, therefore, due to the fact that the .ToString method doesn't have the same verification issues as the static methods, I would conclude that .ToString is the fastest way to get the value as a string.


Best I can find is this unrelated question on MSDN, which contains an XML snippet that answers this question. Any of these methods share the same flaw: they call enum.toString(), which does not work properly when using Dotfuscation. Other concerns appear to relate to indirect boxing (GetName and Format). Unfortunately, I can't find any performance reasons for using any of the above.

Paraphrasing from the xml snippet,

Passing a boxed enum to string.Format() or any other function can result in enum.ToString() being called. This will cause problems when Dotfuscating. You should not use enum.ToString(), enum.GetNames(), enum.GetName(), enum.Format() or enum.Parse() to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.