Answer the question
In order to leave comments, you need to log in
Is it possible to access different C# constructors through one object?
Such is the question ... there are 2 classes. 1 main second for field initialization in which there are 2 constructors.
class Animal
{
public string kindOfAnimal;
protected int numberOfLegs;
private string presenceTail;
public Animal(string aKindOfAnimal, int aNumberOfLegs)
{
kindOfAnimal = aKindOfAnimal;
numberOfLegs = aNumberOfLegs;
presenceTail = " - ";
}
public Animal(string aKindOfAnimal, int aNumberOfLegs, string aColor)
{
kindOfAnimal = aKindOfAnimal;
numberOfLegs = aNumberOfLegs;
presenceTail = aColor;
}
Animal animal = new Animal(textBox1.Text, Convert.ToInt32(textBox2.Text), textBox3.Text);
Answer the question
In order to leave comments, you need to log in
Use the default parameters and or constructor chaining, you can also use the factory pattern that it has already constructed for you, depending on the parameters
Well, the most primitive thing in the forehead is to check if the entered text has a color, if not, then create an object through the constructor without it.
But it's better to drag this check into the second constructor, and there already check if the color is empty, then it's a dash. And get rid of the first constructor.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question