Hi Guys
NP46 constructor & non-constructor
Though output is same in the following programs one is using constructor method other one is not.
I wish to know in what circumstances we have to decide which method is suitable. Anyone knows please explain.
Thank you
using System;
public class CreateEmployee
{
public static void
{
Employee myAssistant = new Employee();
myAssistant.IDNumber = 345;
Console.WriteLine("ID # is {0}", myAssistant.IDNumber);
}
}
class Employee
{
private int idNumber;
public int IDNumber
{
get{ return idNumber; }
set{ idNumber = value; }
}
}
//ID # is 345
using System;
public class CreateEmployee
{
public static void
{
Employee myAssistant = new Employee(345);
Console.WriteLine("ID # is {0}", myAssistant.IDNumber);
}
}
class Employee
{
private int idNumber;
public Employee(int i)
{
idNumber = i;
}
public int IDNumber
{
get { return idNumber; }
}
}
//ID # is 345
Posted Sep 29, 2007, 6:57 PM
Thank you very much for your explanation, Alan
AlanPosted Sep 29, 2007, 6:25 PM
Although it may not look like it, you are in fact calling a constructor with both pieces of code.
In the second case, the constructor is explicitly defined and requires an int argument.
In the first clase, the constructor is supplied by the system and looks like this:
public Employee() : base()
{
}
In other words it is public, parameterless and all it does is to call the base class's parameterless constructor.
As to which is preferable, I would say the explicit constructor in this case because you want to supply an idNumber for an Employee at the point of construction rather than risk leaving it with the default value of 0 until such time as you remember to set the IDNumber property.