I am facing a problem.
I have an enum which further goes as some string values.
Now I have a check or validation for that particular enum type as if it is null, then
display some error message.

But when I give nothing for the particular parameter, it takes the first value from the enum
which is wrong and I do not get the error message at all.

what should I have to do for the validation for null values or when user does not entered any value?
I do not want enum to set the default value as the first one.

9 Years
Discussion Span
Last Post by sknake

Maybe setting the first enum as an Error so when they do not give a value then you can tell they didn't supply a value.


I experienced the same problem when I was writing my data layer ---

                 * If an ENUM fails to parse it will default to the first value.
                 * I hope whatever enum this is has an UNKNOWN defined in the first ordinal position :)
                fp.FI.SetValue(this, Enum.Parse(fp.FI.FieldType, Convert.ToString(row[dc.ColumnName])));

As far as what you can do to handle it you need to check the value before you try to assign the enum. If its a combo box then show an error message and don't let them save the data. If you're loading data from a database and parsing an enum from the string value then you have to assign some value to the enum OR you can use Nullable<> Here is a nullable example:

enum MyEnum

    private void button3_Click(object sender, EventArgs e)
      List<string> stringValues = new List<string>();
      stringValues.Add("Invalid Value");

      List<MyEnum?> enumValues = new List<MyEnum?>();
      List<Nullable<MyEnum>> enumValues2 = new List<MyEnum?>(); //same as above. '?' is easier to read for me
      foreach (string s in stringValues)
          object o = Enum.Parse(typeof(MyEnum), s);
        catch (ArgumentException)
          enumValues.Add(null); //it was not found
      //At this point enumValues' third item is a null since it was invalid
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.