How to restrict a set of a property?

1

I have the following property in my class:

public char Naipe { get; set; }

This property can only receive one of the following values:

(char)9824 (Espada)

(char)9827 (Paus)

(char)9829 (Copas)

(char)9830 (Ouro)

These are Unicode decimal encodings and represent each suit of a deck.

How can I limit this property to be able to receive only these values?

    
asked by anonymous 16.12.2017 / 16:13

2 answers

5

Gambi alert

Use an enumeration:

using static System.Console;

public class Program {
    public static Naipe Naipe { get; set; }
    public static void Main() {
        Naipe = Naipe.Copas;
        WriteLine($"{(char)Naipe.Espada} {(char)Naipe.Paus} {(char)Naipe.Copas} {(char)Naipe.Ouro} {(char)Naipe}");
    }
}

public enum Naipe { Espada = 9824, Paus = 9827, Copas = 9829, Ouro }

See running on .NET Fiddle . And in Coding Ground . Also I placed GitHub for future reference .

Not that it's guaranteed, but it's almost, you can get around it, but it's not the standard procedure. If you want to guarantee it would even have to include a validation on the property, but I find it unnecessary, because it will only be done wrong if the person forces. I am against being warned of stubborn programmer, prevention is good to avoid accidents.

This is not correct, but works fine. The workaround would create an attribute on each member of the enumeration with the character, does not compensate.

Another way would be to create a structure with the options and validate it, so it is guaranteed that it will never be something else. And you can easily associate the constant with the Unicode character. I do not think it's necessary, but it's better than validating on the property.

    
16.12.2017 / 16:30
4

Another way to do this is to expand the property and apply its logic

private char[] naipesPermitidos = new char[] {(char)9824, (char)9827, ...};
private char naipe;
public char Naipe {
    get {
        return naipe;
    }
    set {
        if (naipesPermitidos.Contains(value)) {
            naipe = value; // troca o valor
        } else {
            // e o que fazer quando não for um valor permitido?
        }
    }
}
    
16.12.2017 / 16:31