C # - Return Enum? from static extension method

I added some extension methods for strings to make it easier to work with some custom enums.

public static Enum ToEnum<T>(this string s)
{
    return (Enum)Enum.Parse(typeof(T), s);
}

public static bool IsEnum<T>(this string s)
{
    return Enum.IsDefined(typeof(T), s);
}

Note. Due to limitations of general type restrictions, I have to write methods like the ones above. I would like to use T ToEnum (this line is s), where T: Enum, to avoid casting after making a call ... but can't do it.

Anyway, I thought it would be nice to extend this concept a bit to bring back Enum? in cases where the method signature can accept various null enumerations.

public static Enum? ToEnumSafe<T>(this string s)
{
    return (IsEnum<T>(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
}

However, this is not-go due to compiler errors.

error CS0453: The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

, Enum? , ?. - , .

public static T? ToEnumSafe<T>(this string s)
{
    return (IsEnum<T>(s) ? (T)Enum.Parse(typeof(T), s) : null);
}

, :

public static bool IsEnum(this string s, Type T)
{
    return Enum.IsDefined(T, s);
}
public static Enum? ToEnumSafe(this string s, Type T)
{
    return (IsEnum(s, T) ? (Enum)Enum.Parse(T, s) : null);
}

- ?

+3
4

Try:

public static T? ToEnumSafe<T>(this string s) where T : struct
{
    return (IsEnum<T>(s) ? (T?)Enum.Parse(typeof(T), s) : null);
}
+5

, - .

# , , T , CLR . Unconstrained Melody, " , ". , , ( , ). IsDefined(string), TryParse, .

. .

, Enum? - System.Enum ( System.ValueType), . ? , .

+3
public static Enum ToEnum<T>(this string s)
{
    return (Enum)Enum.Parse(typeof(T), s);
}

public static T ToEnum<T>(this string s)
{
    return (T)Enum.Parse(typeof(T), s);
}

can also fix the following

public static Enum? ToEnumSafe<T>(this string s)
{
    return (IsEnum<T>(s) ? (Enum)Enum.Parse(typeof(T), s) : null);
}

to

public static T? ToEnumSafe<T>(this string s)
    where T : struct
{
    return (IsEnum<T>(s) ? (T?)Enum.Parse(typeof(T), s) : null);
}
0
source

Enum is not a separate type in .Net, it is just a placeholder for a specific type of value (int, unless you specify otherwise).

This means that you cannot have it as a type declaration at all (regardless of the static extension method or not).

0
source

Source: https://habr.com/ru/post/1719924/


All Articles