So, I have this program that has a constructor with the inputs as DateTime.
But whenever I try to create the object of that Class, and pass the DateTime as argument, there is an error.
The code is as follows:
public Student(DateTime dob)
{
DateofBirth = dob;
}
}
class Program
{
static void Main(string[] args)
{
var myprogram = new Student(1995,04,29);
But, it's showing error in the Student class stating that constructor cannot take three arguments. Please help!
PS: There is code above and below, so ignore the brackets.
Well yes - you're trying to pass three integer arguments to the constructor, but it accepts a DateTime
value. You're not currently creating a DateTime
value. All you need to do is change your constructor call to:
var myprogram = new Student(new DateTime(1995, 4, 29));
This will not happen implicitly - you need to tell the compiler that you really did mean to create a DateTime
.
As an alternative you could add a Student
constructor to create the DateTime
and chain to the other constructor:
public Student(int year, int month, int day)
: this(new DateTime(year, month, day))
but that doesn't seem like a good idea to me for a Student
class.
See more on this question at Stackoverflow