2

I have 2 Nullable Datetime field's in a method. How to select minimum of 2.

I tried below:

    static void GetMinimunDate(DateTime? startDate,DateTime? copDateTime)
    {
         DateTime? retDate = DateTime.MinValue;

        if (startDate == null && copDateTime == null)
        {

        }
        else if(startDate.HasValue && copDateTime.HasValue)
        {
            retDate = startDate < copDateTime ? startDate : copDateTime;
        }
        else if (startDate == null)
        {
            retDate = copDateTime;
        }
        else
        {
            retDate = startDate;
        }
    }
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54
user2159471
  • 313
  • 2
  • 12
  • Just compare their `Value` properties and see which one is smaller. – Soner Gönül Nov 19 '15 at 08:17
  • 1
    So where's the problem – Rahul Nikate Nov 19 '15 at 08:17
  • Want to check if there is a better way. If one is null i want other value – user2159471 Nov 19 '15 at 08:19
  • You can write a generic method to calculate Min or Max for any type like below: `public static T Max(T FirstArgument, T SecondArgument) { if (Comparer.Default.Compare(FirstArgument, SecondArgument) > 0) return FirstArgument; return SecondArgument; }` Then use like below: `var result = new[]{datetime1, datetime2, datetime3}.Max();` – Rahul Nikate Nov 19 '15 at 08:43
  • public static DateTime? Min(DateTime? firstArgument, DateTime? secondArgument) { if (Nullable.Compare(firstArgument, secondArgument) > 0) return firstArgument; return secondArgument; } – Vahid Jafari Sep 07 '20 at 10:13

0 Answers0