How to restrict a set of a property?

Asked

Viewed 81 times

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 to limit this property to be able to receive only these values?

  • By syntax it is not possible to do this, but through a gambit...

  • Have any answers solved what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

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 }

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Not that it’s a sure thing, but it’s close, you can get around it, but it’s not standard procedure. If you want to guarantee it would have to include a validation in the property, but I think it is unnecessary, because it will only be done wrong if the person forces it. I am against preventing stubborn programmer, prevention is good to prevent accidents.

This is not the most correct, but it works well. The alternative solution would create an attribute in each member of the enumeration with the character, it 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 anything else. And you can easily associate the constant with the Unicode character. I don’t think it’s necessary, but it’s better than validating in the property.

4

Another way to do it 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?
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.