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.

Recommended Answers

All 3 Replies

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 ---

try
              {
                /*
                 * 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
    {
      Value1,
      Value2
    }

    private void button3_Click(object sender, EventArgs e)
    {
      List<string> stringValues = new List<string>();
      stringValues.Add("Value1");
      stringValues.Add("Value2");
      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)
      {
        try
        {
          object o = Enum.Parse(typeof(MyEnum), s);
          enumValues.Add((MyEnum)o);
        }
        catch (ArgumentException)
        {
          enumValues.Add(null); //it was not found
        }
      }
      //At this point enumValues' third item is a null since it was invalid
      System.Diagnostics.Debugger.Break();
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.