CipherIS
asked on
C# Create method with generic enum as parameter
How can I pass a generic Enum to a method? I want to pass any enum object to the below method. Receiving error on "enum" parameter. Error is "type or namespace enumName not found".
public static bool FindExcludedFields(string value, Enum enumName)
{
try
{
enumName column =
(enumName)Enum.Parse(typeof(enumName), value);
//Enumerators.ExcludedItemsFields column =
// (Enumerators.ExcludedItemsFields)Enum.Parse(typeof(Enumerators.ExcludedItemsFields), value);
//if (Enum.IsDefined(typeof(Enumerators.ExcludedItemsFields), column))
if (Enum.IsDefined(typeof(enumName), column))
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
ASKER
Made the below changes but "enumType" in the try is giving an error -> "Type or namespace enumType could not be found are you missing a directive or namespace?
public static bool FindExcludedFields(string value, Type enumType)
{
try
{
enumType column = (enumType)Enum.Parse(typeof(enumType), value);
if (Enum.IsDefined(typeof(enumType), column))
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
ASKER
This works.
public static class EnumValidation
{
public static bool FindExcludedFields<T>(string value)
{
try
{
if (typeof(T).IsEnum)
{
T column = (T)Enum.Parse(typeof(T), value);
if (Enum.IsDefined(typeof(T), column))
return true;
else
return false;
}
else
{
throw new ApplicationException("Enum is not valid");
}
}
catch (Exception ex)
{
return false;
}
}
}
ASKER
@Russ - any thoughts?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window