D
D
devilong2020-05-15 19:40:41
C++ / C#
devilong, 2020-05-15 19:40:41

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;
        }


In main class I create class object and pass strings
Animal animal = new Animal(textBox1.Text, Convert.ToInt32(textBox2.Text), textBox3.Text);

but it works only through 1 constructor with 3 lines accepting .... how to make 2 constructors work from 1 object?
For example, I entered all 3 lines, one constructor worked, I typed only 2 lines, another constructor worked.

And the question is how to make a destructor for the second class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Korotenko, 2020-05-16
@devilong

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

F
freeExec, 2020-05-15
@freeExec

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 question

Ask a Question

731 491 924 answers to any question