1
This is the code where I defined a class Animal
is a breeding method that asks the species of the animal and defines its state as alive:
public class Animal
{
public bool estaVivo, usaDrogas = false;
string Especie;
public Animal()
{
bool estaVivo = true;
Console.WriteLine("Qual a espécie desse animal?");
Especie = Console.ReadLine();
Console.WriteLine(estaVivo);//debug
}
Next, I have the domestic class, which inherits from Animal
public class Domestic : Animal
{
public Domestico()
{
Console.WriteLine("Qual o nome do seu bicho de estimação?");
Nome = Console.ReadLine();
Console.WriteLine("Qual a idade do seu bicho de estimação? (NUMERIC)");
Idade = Convert.ToInt32(Console.ReadLine());
}
}
Finally the main method where I instate the object:
static void Main(string[] args)
{
Domestico bicho = new Domestico();
Console.WriteLine(bicho.estaVivo);//debug
Console.ReadKey();
}
The question is, why when the constructor method of the class Animal
is called the value of this living is True
, as intended, but when I introduce the derived class Domestico
the value becomes False
(and besides I can’t change its value).
It worked well, had not noticed that I had declared the variable within the constructor. After all, I had already seen your answer about the use of constructors, that’s when I decided to do this test, to find out how a constructor works in C#. Besides, I ended up learning to use the keyword
this
.– Ezequiel Barbosa
The
this
is much more than this but its main feature is to disambiguate local instance variables.– Maniero