0

What attribute in C# can limit public char gender to M, F and O only, otherwise an error message will appear?

Dylan Czenski
  • 1,305
  • 4
  • 29
  • 49

2 Answers2

3

there is no such attribute but you can do something like this.

public class FOO 
        {
            private char _foo;
            public char foo 
            {
                get { return _foo; }
                set {
                    if (value == 'M' || value == 'F' || value == 'O')
                    {
                        _foo = value;
                    }
                    else 
                    {
                        throw new Exception("invalid Character");
                    }
              }
            }
        }

or you can try ENUM and bind it with interface as you want.

public enum Gender 
{ 
    M,
    F,
    O
}

and you can use it here

public class FOO 
{
   public Gender gender {get;set;} 

}
sm.abdullah
  • 1,777
  • 1
  • 17
  • 34
  • Thank you. In the first approach, which one is mapped to the SQL table, `_foo` or `foo`? – Dylan Czenski Dec 29 '15 at 16:03
  • 1
    foo is the property which is public. where _foo is the private feild. http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property-in-c – sm.abdullah Dec 29 '15 at 16:07
1

Enums are really good when you don't need a value to store. When you do need one (which in this case I think you do) I prefer using a public static class as follows:

public static class Gender
    {
        public const char Male = 'M';
        public const char Female = 'F';
        public const char Other = 'O';

    }

You can then use it similar to an enum but in this case you actually have a value:

Gender.Male
Starceaker
  • 631
  • 2
  • 5
  • 14