1
 public class myclass
    {
        public Details DetailsInfo { get; set; }
        public string name{ get; set; }
        public string Email { get; set; }
        public int subjects{ get; set; }
    }

public enum subjects{
maths,
english,
science,
}

Among these subjects is an enum. Even if I don't enter any value for subjects it takes 0 by default. This is the behavior of enum. Is there any way to check if I have chose any value for subject.

Note: I don't want to any value like undefined in the enum.

rene
  • 41,474
  • 78
  • 114
  • 152
kanmani1303
  • 85
  • 3
  • 13
  • 3
    That the reason why any Enum should have a `None` value that represents 0. You can use a nullable enum. – Sebastian Schumann May 12 '16 at 07:59
  • 1
    Enum is not a `class` (or, to be more precise, not a reference type). Hence it does not have `null` as value. If you want enum to have `null`, you could use nullable enum: http://stackoverflow.com/questions/4337193/how-to-set-enum-to-null – Ian May 12 '16 at 08:01

2 Answers2

5

You could solve the issue in two ways.

First, define a None value (or whatever you want to name it) which represents 0 to indicate there is nothing chosen for an enum value:

public enum subjects{
    None = 0, //define this
    maths,
    english,
    science,
}

Alternatively, use Nullable<subjects> or subjects? in your class (myclass).

public class myclass
{
    public Details DetailsInfo { get; set; }
    public string name{ get; set; }
    public string Email { get; set; }
    public subjects? subj { get; set; } //note the question mark ?
}           

Of the two methods, the first one is more common. Thus I would rather use the first one.

Ian
  • 30,182
  • 19
  • 69
  • 107
0

You can change the class to look like this:

 public class myclass
    {
        public Details DetailsInfo { get; set; }
        public string name{ get; set; }
        public string Email { get; set; }
        public subjects? subject { get; set; }
    }

So that the subject is nullable. It means that when you have not set it. It will be null

Arion
  • 31,011
  • 10
  • 70
  • 88