What attribute in C# can limit public char gender to M, F and O only, otherwise an error message will appear? 
            Asked
            
        
        
            Active
            
        
            Viewed 687 times
        
    0
            
            
         
    
    
        Dylan Czenski
        
- 1,305
- 4
- 29
- 49
- 
                    what about an enum and radio buttons instead of having to validate that the user typed in a valid char, which seems awkward for both sides – Jonesopolis Dec 29 '15 at 15:43
- 
                    5like `public enum Gender { Male, Female, Other }` and property `public Gender UserSelectedGender {get; set;}` – Jonesopolis Dec 29 '15 at 15:46
- 
                    For everything you can't expect a attribute ... right? – Rahul Dec 29 '15 at 15:51
2 Answers
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
- 
                    1foo 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
- 
                    1Nice solution but the other one is better in my case. Thank you! – Dylan Czenski Dec 29 '15 at 16:09