Reputation: 343
Hello i am doing a school assignment. Everything in my program works fine but the teacher wants me to add a parameter of type DateTime in one of my constructors. I am a bit confused since i think that i already have a parameter of this type:
using System;
using System.Windows.Forms;
namespace Assignment4
{
class Task
{
private string time = string.Empty;
private string date = string.Empty;
private DateTime dateTime = new DateTime();
private string description = string.Empty;
private object priorityType;
private string priority;
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public DateTime DateTime
{
set
{
dateTime = value;
time = dateTime.TimeOfDay.ToString();
date = dateTime.Date.ToString("d");
}
}
public string Time
{
get
{
return time;
}
}
public string Date
{
get
{
return date;
}
}
public object PriorityType
{
set
{
priorityType = value;
priority = priorityType.ToString();
}
}
public string Priority
{
get
{
return priority;
}
}
}
}
Is dateTime = value not a parameter of type DateTime?
Upvotes: 0
Views: 49
Reputation: 216291
The constructor of a C# class is a method without a return type and with the same name of the class. The constructor is called everytime you create an instance of the class (new YourClass).
You can have many constructors with different kind of parameters passed to these methods, even one without parameters (it is the default constructor).
The correct constructor is identified by the parameters that you pass when you create the class....
public class Person
{
private string _name;
private DateTime _dob;
public Person(string name, DateTime dateOfBirth)
{
_name = name;
_dob = dateOfBirth;
}
}
..... somewhere in your code .....
Person myself = new Person("Steve", new DateTime(1970,1,1));
Upvotes: 2
Reputation: 156978
Since DateTime
is an immutable struct, you can only set its values from the constructor. That means you need to do something like this:
dateTime = new DateTime(2016, 05, 03);
In your case, you can just use this, since you set it somewhere else:
private DateTime dateTime;
(Also, your property needs a get
too, you just have a set
now)
Upvotes: 1