Jablonovo Jablonovo - 15 days ago 7
C# Question

Constructor chaining with class as parameter

Question about chaining constructor with Class Parameter.

I have three classes and I want to pass one of the class to the other one with mainclass as base. better to show you.

public partial class Form1 : Form
{

public Form1()
{

InitializeComponent();
int value = 22;

ClassToPass toto = new ClassToPass();
OtherClass TheOther = new OtherClass(value,toto);
OtherClass TheOther2 = new OtherClass(value);
//but I can't do
OtherClass NotPossible = new OtherClass(toto);
}
}
public class ClassToPass
{
public int num = 0;
}


I cannot make the line NotPossible come true...
The Other Class looks like this with three constructor chained.

class OtherClass
{
int Numeral = 2;
ClassToPass classtestinside;

public OtherClass()//default ctor
{}

public OtherClass(int valuereceived)
: this(valuereceived, ClassToPass missingsomething)//only int ctor
{}

public OtherClass( ClassToPass _Classtest)//classtopass ctor
: this(int 0)
{}

public OtherClass(int valuereceived, ClassToPass _Classtest)//master ctor
: this()
{
Numeral = valuereceived;
classtestinside = _Classtest;
classtestinside.num = 34;
}
}


What do I need to pass as initialisation in missingsomething second constructor?
I tried null but it seems not working.

Thanks A lot

Ok...
I have a Form with a list box. This form is for debug purpose.
When I instanciate all my object (Class) I want them to write in this list box what is happened.
So I pass the debug class as parameter to other class so that everybody (class) now who is this listbox.
I pass the text with delegate callback to write from each class to the listbox debug. The problem is that others want to call my classes (not the debugger) and they want to send me a string.
So I'm trying to use chained constructor so that when I instanciate my classes is with the debugger class in parameter and when THEY call my classes they do with a string as parameter.

I put some code tomorrow... is that the wrong way?

Answer

You need to modify these constructor

    public class ClassToPass
    {
        public int num = 0;
    }

    class OtherClass
    {
        int Numeral = 2;
        ClassToPass classtestinside;

        public OtherClass()//default ctor
        {}

        public OtherClass(int valuereceived): this(valuereceived, null)//only int ctor
        {}

        public OtherClass( ClassToPass _Classtest)//classtopass ctor
        : this(0, _Classtest)
        {
        }
        public OtherClass(int valuereceived, ClassToPass _Classtest)//master ctor
            : this()
        {
            Numeral = valuereceived;
            if (_Classtest != null)
            {
                classtestinside = _Classtest;
                classtestinside.num = 34;
            }
        }
    }
Comments