System.Enum.ToString C# (CSharp) Method

ToString() public method

public ToString ( ) : String
return String
        public override String ToString()
        {
            // Returns the value in a human readable format.  For PASCAL style enums who's value maps directly the name of the field is returned.
            // For PASCAL style enums who's values do not map directly the decimal value of the field is returned.
            // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant
            //(a pure power of 2), then the  OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of
            // pure powers of 2 OR-ed together, you return a hex value
            Type eT = this.GetType();
            FieldInfo thisField = GetValueField(eT);

            // Retrieve the value from the field.
            Object value = ((RtFieldInfo)thisField).InternalGetValue(this, false);

            //Object value = ((RuntimeFieldInfo)thisField).GetValueInternal(this);
            return InternalFormat(eT, value);
        }
        #endregion

Same methods

Enum::ToString ( IFormatProvider provider ) : String
Enum::ToString ( String format ) : String
Enum::ToString ( String format, IFormatProvider provider ) : String

Usage Example

        private string GetEnumDescription(System.Enum objEnum)
        {
            var fieldInfo      = objEnum.GetType().GetField(objEnum.ToString());
            var attributeArray = fieldInfo.GetCustomAttributes(false);

            if (attributeArray.Length == 0)
            {
                return(objEnum.ToString());
            }
            else
            {
                DescriptionAttribute descAttribute = null;

                foreach (var atb in attributeArray)
                {
                    if (atb is DescriptionAttribute)
                    {
                        descAttribute = atb as DescriptionAttribute;
                    }
                }

                if (descAttribute != null)
                {
                    return(descAttribute.Description);
                }

                return(objEnum.ToString());
            }
        }
All Usage Examples Of System.Enum::ToString