How do I validate an enum parameter on a public method?

I have this extension method for an Enum:

public static List<Enum> Values(this Enum theEnum)
{
    return Enum.GetValues(theEnum.GetType()).Cast<Enum>().ToList();
}

I'm getting a code analysis violation:

CA1062 Validate arguments of public methods
In externally visible method 'EnumExtensions.Values(this Enum)', validate parameter 'theEnum' before using it.

Why is that happening? How can I validate the parameter? I can't check for null because an enum is a non-nullable value type. Is there some other check that is supposed to be occurring here?

Jon Skeet
people
quotationmark

I can't check for null because an enum is a non-nullable value type.

Any particular enum is a value type, but Enum itself isn't. (Just like ValueType isn't a value type either... every type derived from ValueType except Enum is a value type.)

In other words, I could write:

Enum foo = null;
var bang = foo.GetValues();

That would compile and then fail at execution time with a NullReferenceException.

Given that you ignore the value except to get its type, I'd actually suggest removing it and either accepting a Type or making it generic in the type of enum you want. But if you want to keep the current signature, you just need:

if (theEnum == null)
{
    throw new ArgumentNullException();
}

You might also want to look at my Unconstrained Melody project which provides a bunch of helper methods for enums, generically constrained to enum types via IL manipulation.

people

See more on this question at Stackoverflow