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 , a name and a suit .
-
The
Valor
property corresponds to the range of 2 to 14 (this rule was implemented inset
of property). -
The
Nome
property is derived fromValor
and only converts some numbers into letters. That is, the range of 2 to 9 will have their respective names as their names, and the range between 10 and 14 will have the names T, J, Q, K and A). -
Naipe
is achar
that will store a Unicode character.
Since it does not make sense to have a worthless letter, I have created a constructor. But I can not set the Value property through this constructor, the IDE has an error that is only solved if I set a number to _valor
in the constructor (but it does not go through validation and the Value property goes out of function). How to proceed?
The displayed error is:
The 'this' object can not 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;
}
}