P
P
Porohkun2013-11-13 15:02:30
C++ / C#
Porohkun, 2013-11-13 15:02:30

How to pass control to another constructor?

Let's say I have a class:

public class test
{
   int _IntValue;
   string _StringValue;

   public test(int i)
   {
       _IntValue=i;
   }

   public test(int i, string s)
   {
       //тут надо бы выполнить код из первого конструктора
       _StringValue = s + _IntValue;
   }
}

How can I make it so that when the second constructor is called, the code from the first one is executed first, and only then from the second one (well, or vice versa, it doesn’t matter) I’m
interested in the option without implementation through inheritance or through highlighting the code of the first constructor into a separate procedure.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2013-11-13
@Porohkun

public test(int i, string s) : this(i)
{
    _StringValue = s + _IntValue;
}

K
KotAA, 2013-11-13
@KotAA

public class test
{
   int _IntValue;
   string _StringValue;

   public test(int i)
   {
       _IntValue=i;
   }

   public test(int i, string s)
   {
       //тут надо бы выполнить код из первого конструктора
       this.test(i);

       _StringValue = s + _IntValue;
   }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question