http://www.c-sharpcorner.com/Forums/Thread/277334/constructor-body.aspx
I wish to know whether it is possible to do in the following program the way code is highlighted in the above web page. Problem is coloured.
using System;
public class CreateEmployee
{
public static void Main()
{
int id = 345;
Employee myAssistant = new Employee(id);
Console.WriteLine("ID # is {0}", myAssistant.GetId());
Console.ReadKey();
}
}
internal class Employee
{
private int idNumber;
public Employee(Employee myA)
{
idNumber = myA.idNumber;
}
public int GetId()
{
return idNumber;
}
}
// ID # is 345
Loading

VulpesPosted Mar 16, 2015, 7:12 AM
However, it will work if you add the highlighted code:
MahaPosted Mar 16, 2015, 10:41 AM
MahaPosted Mar 16, 2015, 6:42 AM
public Employee(Employee myA)
{
idNumber = myA.idNumber;
}
Why it is incorrect to write following way
public Employee(Employee myA)
{
idNumber = (int)myA;
}
MahaPosted Dec 3, 2014, 9:07 AM
Michal HabalcikPosted Dec 3, 2014, 8:55 AM
VulpesPosted Dec 3, 2014, 8:53 AM
That certainly does create an infinite sequence of constructor calls leading to an out of memory exception.
However, copy constructors are OK - they're used in C++ all the time - and the code I posted above compiles and runs fine.
VulpesPosted Dec 3, 2014, 8:46 AM
http://msdn.microsoft.com/en-us/library/ms173116.aspx
Michal HabalcikPosted Dec 3, 2014, 8:45 AM
Also, the whole principle is just wrong. You can't use the class in its own constructor like this.
The constructor awaits the Employee and that Employee again awaits Employee in the constructor.
Something like:
VulpesPosted Dec 3, 2014, 8:41 AM
I've altered your code to achieve it here:
using System;
public class CreateEmployee
{
public static void Main()
{
int id = 345;
Employee myAssistant = new Employee(id);
Console.WriteLine("ID # is {0}", myAssistant.GetId());
Employee myAssistant2 = new Employee(myAssistant);
Console.WriteLine("ID # is {0}", myAssistant2.GetId());
Console.ReadKey();
}
}
internal class Employee
{
private int idNumber;
public Employee(int id)
{
idNumber = id;
}
public Employee(Employee myA)
{
idNumber = myA.idNumber;
}
public int GetId()
{
return idNumber;
}
}
// ID # is 345