Search code examples
c#datetimeicollection

Why can't I call a DateTime method on a DateTime object in another class in C#


Ive found a few examples of this problem in other languages such as ruby or php and they seem to indicate that I would need to have some sort of include to support this but I can't exactly figure it out.

I have:

private void setLoansView(Member _member)
{

    foreach (Loan loan in _member.Loans)
        {
            this.dt.Rows.Add(_member.Name, // dt is a datatable 
                   loan.BookOnLoan.CopyOf.Title, 
                   loan.TimeOfLoan.ToShortDateString(), 
                   loan.DueDate.ToShortDateString(), 
                   loan.TimeReturned.ToShortDateString());
        }

Loan looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Library.Entities
{
    public class Loan
    {
        [Key]
        public int LoanId { get; set; }
        [Required]
        public DateTime? TimeOfLoan { get; set; }
        public DateTime? DueDate { get; set; }
        public DateTime? TimeReturned { get; set; }
        [Required]
        public Copy BookOnLoan { get; set; }
        [Required]
        public Member Loanee { get; set; }
    }
}

On all my DateTime objects in the setLoansView() method I get 'does not contain definition for "ToShortString()". The Member class has an ICollection<Loan> and thats where Im retrieving the loans from. I can't figure out why I loose access to DateTime's methods when I access them from the ICollection though.


Solution

  • That's because the type of these properties is not DateTime, but Nullable<DateTime>. Nullable<T> does not expose such a method.

    If you are sure that these dates will have a value, interpose .Value before .ToShortDateString(). If not, you have to decide what should happen in that case.