Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question about constructors in C#

Tags:

c#

constructor

Hi
About this partial code in a class which is named Square :

public Square( int i_RowIndex, eColumn i_ColIndex) 
{
    m_RowIndex = i_RowIndex;
    m_ColIndex = i_ColIndex;
    **new Square(i_RowIndex, i_ColIndex, eCoinType.NoCoin);**
}

public Square(int i_RowIndex, eColumn i_ColIndex, eCoinType i_CoinType) 
{
    m_RowIndex = i_RowIndex;
    m_ColIndex = i_ColIndex;
    m_Coin = i_CoinType;
}

Is it right that it is not good to call an overloaded C'tor within other C'tor and with a "new" statement like you see in bold? I think this is wrong , and every time we call new we allocate a new instance and it is not right to allocate 2 duplicate instances from C'tor which meant to allocate one instance from the first place.

Am I wrong?

Thanks

like image 325
Mulder Avatar asked Nov 27 '25 09:11

Mulder


2 Answers

You shouldn't call an overload constructor from within a constructor, that'd create a new instance.

Should be more like:

public Square( int i_RowIndex, eColumn i_ColIndex)
    : this(i_RowIndex, i_ColIndex, eCoinType.NoCoin)
{
}

public Square(int i_RowIndex, eColumn i_ColIndex, eCoinType i_CoinType) 
{
    m_RowIndex = i_RowIndex;
    m_ColIndex = i_ColIndex;
    m_Coin = i_CoinType;
}    
like image 123
Jonathan Avatar answered Nov 29 '25 22:11

Jonathan


It's not right. In fact, this sentence:

new Square(i_RowIndex, i_ColIndex, eCoinType.NoCoin);

Does absolutely nothing (useful) on your constructor.

like image 36
Pablo Santa Cruz Avatar answered Nov 29 '25 23:11

Pablo Santa Cruz