CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2014
    Posts
    4

    Nullable DateTime in method signature

    Hi,
    How do you handle nullable datetimes in method signatures?

    Sample code:

    Code:
            public ViewResult ShipCalendarMonth(int Id, DateTime? dt)
            {
                if (dt == null) { dt = DateTime.Now; }
    
                var shipCalendar = repo.CruiseCalendarDays(Id, dt, 28);
                return View(shipCalendar);
            }
    I get a red squiggle over the 'dt' parameter in repo.CruiseCalendarDays, because it expects a nonnullable datetime.

    How should I approach this?

    regards, Guy

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Nullable DateTime in method signature

    Code:
    public ViewResult ShipCalendarMonth(int Id, DateTime? dt)
    {
        var shipCalendar = repo.CruiseCalendarDays(Id, dt.HasValue ? dt.Value : DateTime.Now, 28);
        return View(shipCalendar);
    }

  3. #3
    Join Date
    Apr 2014
    Posts
    4

    Re: Nullable DateTime in method signature

    Quote Originally Posted by Arjay View Post
    Code:
    public ViewResult ShipCalendarMonth(int Id, DateTime? dt)
    {
        var shipCalendar = repo.CruiseCalendarDays(Id, dt.HasValue ? dt.Value : DateTime.Now, 28);
        return View(shipCalendar);
    }
    Thanks Arjay!

    Code:
    This also works (just stumbled across it)
    
            public ViewResult ShipCalendarMonth(int Id, DateTime? dt)
            {            
                DateTime startDate = dt ?? DateTime.Now;
                var shipCalendar = repo.CruiseCalendarDays(Id, startDate, 28);
                return View(shipCalendar);
            }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured