Is there a way to check if int is legal enum in C#?

I’ve read a few SO posts and it seems most basic operation is missing.

public enum LoggingLevel
{
    Off = 0,
    Error = 1,
    Warning = 2,
    Info = 3,
    Debug = 4,
    Trace = 5
};

if (s == "LogLevel")
{
    _log.LogLevel = (LoggingLevel)Convert.ToInt32("78");
    _log.LogLevel = (LoggingLevel)Enum.Parse(typeof(LoggingLevel), "78");
    _log.WriteDebug(_log.LogLevel.ToString());
}

This causes no exceptions, it’s happy to store 78. Is there a way to validate a value going into an enum?

9 Answers
9

Leave a Comment