I have created a constructor as follows :
public Animal(string regNum, DateTime brought, string name)
{
this.RegNumber = regNum;
this.DateBrought = brought;
this.Name = name;
this.NameNewOwner = null;
}
And based on the constructor above, I created an object called pet
, as follows:
Animal pet = new Animal("a12344", Convert.ToDateTime(23/01/2013), "Fluffy");
However, when I run my program it gives me error saying: Invalid cast from Int32 to DateTime
Can anyone help me with this?
Constructor is not a problem. Convert.ToDateTime
call is:
Convert.ToDateTime(23 / 01 / 2013);
It's equivalent to Convert.ToDateTime(0)
(because 23/1/2013
as integer division returns 0
), which is not possible.
Use new DateTime(2013, 1, 23)
instead.
Animal pet = new Animal("a12344", new DateTime(2013, 1, 23), "Fluffy");
You could also use Convert.ToDateTime("23/01/2013")
, which would be equivalent to DateTime.Parse("21/01/2013")
parsing, but if you know the date at compile time, you should definitely use DateTime
constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.