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


VulpesRank #55 · 29.2K reputationPosted Mar 16, 2015, 3:12 AM EDT
However, it will work if you add the highlighted code:
VulpesRank #55 · 29.2K reputationPosted Dec 3, 2014, 3:46 AM EST
http://msdn.microsoft.com/en-us/library/ms173116.aspx
VulpesRank #55 · 29.2K reputationPosted Dec 3, 2014, 3:41 AM EST
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
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 3, 2014, 3:45 AM EST
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:
VulpesRank #55 · 29.2K reputationPosted Dec 3, 2014, 3:53 AM EST
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.
Michal HabalcikRank #902 · 2.3K reputationPosted Dec 3, 2014, 3:55 AM EST
MahaRank #2,573 · 543 reputationPosted Dec 3, 2014, 4:07 AM EST
MahaRank #2,573 · 543 reputationPosted Mar 16, 2015, 2:42 AM EDT
public Employee(Employee myA)
{
idNumber = myA.idNumber;
}
Why it is incorrect to write following way
public Employee(Employee myA)
{
idNumber = (int)myA;
}
MahaRank #2,573 · 543 reputationPosted Mar 16, 2015, 6:41 AM EDT