Question

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.

Was it helpful?

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.

OTHER TIPS

You have nullable DateTime objects. You'll need to call .Value to get the value (if there is one)

loan.TimeOfLoan.Value.ToShortDateString()

It's nullable, use .Value to get those properties (check if null first)

Because your fields are defined as nullable DateTime?

Just use .Value to access the field's value and you should have your normal DateTime format methods.

Also you should check against null by calling .HasValue

you have a nullable DateTime (DateTime?), only the DateTime class has the "ToShortDateString()" method...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top