Answers for "C#: casting string to enum object"

C#
1

C# .net core convert string to enum

var foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
if (Enum.IsDefined(typeof(YourEnum), foo))
{
    return foo;
}
Posted by: Guest on April-27-2020
1

C#: casting string to enum object

public static T ToEnum<T>(this string value, T defaultValue) 
{
    if (string.IsNullOrEmpty(value))
    {
        return defaultValue;
    }

    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
Posted by: Guest on January-19-2021
-2

C#: casting string to enum object

public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct
{
    TEnum tmp; 
    if (!Enum.TryParse<TEnum>(value, true, out tmp))
    {
        tmp = new TEnum();
    }
    return tmp;
}
Posted by: Guest on January-19-2021

C# Answers by Framework

Browse Popular Code Answers by Language