1
I am creating a simple poker game, in this game I defined that the cards would be structs. According to my business rules, each card has a value, one name and a suit.
The estate
Valorcorresponds to the range of 2 to 14 (this rule has been implemented insetof property).The estate
Nomeis derived fromValorand just converts a few numbers into letters. That is, the range from 2 to 9 will have their respective values as their name, whereas the range between 10 to 14 will have the names T, J, Q, K and Ás).Naipeis acharwhich will store a Unicode character.
As it makes no sense to exist a letter without value I created a builder. Only I can’t set the Value property through this constructor, the IDE accuses an error that is only solved if I set a number to _valor in the constructor (however it does not pass the validation and the property Value is no function). How to proceed?
The error presented is:
The 'this' object cannot be used before all its fields are assigned to
struct Carta
{
private int _valor;
public int Valor {
get {
return _valor;
}
set {
int ValorMaximoPermitido = 14;
int ValorMinimoPermitido = 2;
if (value < ValorMinimoPermitido || value > ValorMaximoPermitido)
{
throw new Exception($"O valor definido para a carta está fora do intervalor entre {ValorMinimoPermitido} e {ValorMaximoPermitido}.");
}
else
{
_valor = value;
}
}
}
public char Naipe { get; }
public string Nome
{
get
{
if (Valor > 1 && Valor < 10)
{
return Valor.ToString() + Naipe;
}
else if (Valor == 10)
{
return "T" + Naipe;
}
else if (Valor == 11)
{
return "J" + Naipe;
}
else if (Valor == 12)
{
return "Q" + Naipe;
}
else if (Valor == 13)
{
return "K" + Naipe;
}
else if (Valor == 14)
{
return "A" + Naipe;
} else
{
throw new Exception($"O nome para {Valor} não foi definido.");
}
}
}
public Carta (int valor, char naipe)
{
Valor = valor;
Naipe = naipe;
}
}
Oh yes I understood, you’re right. It was actually meant to be a
private setI didn’t put it. I did the validation on the set, because in my view since it relates to Value, it seemed a good idea to put the validation there. I’ll useenumjust to help define the suits. Other than this I think there is no way to enter inappropriate data with the business rule.– DanOver
Even private doesn’t make sense. It makes more sense to be an enumeration, but you can do as you wish, I’m not a fan of complexity.
– Maniero