Specified object of the specified type to convert the Enum. - CSharp System

CSharp examples for System:Converter

Description

Specified object of the specified type to convert the Enum.

Demo Code


using System.Xml.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;//  w  ww  . j  av  a2s  .  c om
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Specified object of the specified type to convert the Enum.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <param name="ignoreCase"></param>
        /// <returns></returns>
        public static T IsDefinedAndParseToEnum<T>(Object value, T defaultValue, Boolean ignoreCase) where T : struct
        {
            var s = ToStringOrEmpty(value);
            if (typeof(T).IsEnum == false)
            {
                return defaultValue;
            }
            if (Enum.IsDefined(typeof(T), s))
            {
                return (T)Enum.Parse(typeof(T), s, ignoreCase);
            }
            return defaultValue;
        }
        /// <summary>
        /// Specified object of the specified type to convert the Enum.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T IsDefinedAndParseToEnum<T>(Object value, T defaultValue) where T : struct
        {
            return IsDefinedAndParseToEnum(value, defaultValue, true);
        }
        /// <summary>
        /// Specified object of the specified type to convert the Enum.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="ignoreCase"></param>
        /// <returns></returns>
        public static T? IsDefinedAndParseToEnum<T>(Object value, Boolean ignoreCase) where T : struct
        {
            var s = ToStringOrEmpty(value);
            if (typeof(T).IsEnum == false)
            {
                return null;
            }
            if (Enum.IsDefined(typeof(T), s))
            {
                return (T)Enum.Parse(typeof(T), s, ignoreCase);
            }
            return null;
        }
        /// <summary>
        /// Specified object of the specified type to convert the Enum.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T? IsDefinedAndParseToEnum<T>(Object value) where T : struct
        {
            return IsDefinedAndParseToEnum<T>(value, true);
        }
}

Related Tutorials