'How to use the properties of a class in the same class like they have values in C#
I am trying to use a property of a class in the same class to compare with another value. However, this property is still empty because I do not have an instance of that class. See the example below.
public Zoo(string name, int capacity)
{
Name = name;
Capacity = capacity;
}
public Zoo()
{
AnimalsWhichCouldNotBeModified = new List<Animal>();
}
public List<Animal> AnimalsWhichCouldNotBeModified { get; set; }
public string Name { get; set; }
public int Capacity { get; set; }
public string AddAnimal(Animal animal)
{
// Here I have tried to use the property Capacity.
// I have also tried to use "capacity" from the constructor.
// I have also tried to create an instance of the Zoo class in the Zoo class, but it is still empty, so I am not sure if I can do that.
if (Capacity < AnimalsWhichCouldNotBeModified.Count)
{
return "The zoo is full.";
}
How can I get the capacity (that is still not instanced and it is null) to be used in the example so I can check if the animals are more than the zoo capacity?
Solution 1:[1]
In your second constructor (public Zoo() that doesn't require any other parameters), you could just set your Capacity = 0.
Each time an instance is created, you're either going to use the first constructor, where you need to manually provide a Capacity, or the second constructor that is automatically going to set the Capacity to value 0.
public Zoo(string name, int capacity)
{
Name = name;
Capacity = capacity;
}
public Zoo()
{
Capacity = 0;
AnimalsWhichCouldNotBeModified = new List<Animal>();
}
public List<Animal> AnimalsWhichCouldNotBeModified { get; set; }
public string Name { get; set; }
public int Capacity { get; set; }
public string AddAnimal(Animal animal)
{
// Here I have tried to use the property Capacity.
// I have also tried to use "capacity" from the constructor.
// I have also tried to create an instance of the Zoo class in the Zoo class, but it is still empty, so I am not sure if I can do that.
if (Capacity < AnimalsWhichCouldNotBeModified.Count)
{
return "The zoo is full.";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mario MateaÈ™ |
