0

I am using below code to check null value for Datetime , when modifieddate has value it works fine but when any of the value for modifieddate is null it breaks saying "Object reference not set". How i can handle it ?

public DateTime? modifiedDate { get; set; }   

var lst = outObject.response.docs.Select(b => 
new finalOutput {modifiedDate = b.last_modified[0].HasValue ? b.last_modified[0] : DateTime.Now }).ToList<finalOutput>();

I tried as suggested in the link, it does not work

modifiedDate =  b.last_modified[0].GetValueOrDefault(DateTime.Now) //Object reference error
Bokambo
  • 4,204
  • 27
  • 79
  • 130
  • I tried as suggested in the link, it does not work modifiedDate = b.last_modified[0].GetValueOrDefault(DateTime.Now) //Object reference error – Bokambo Oct 02 '18 at 20:54
  • 1
    You either need to find which part is zero: b, b.last_modified, or b.last_modified[0]. Currently you are only checking for the latter. Or, to be on the safe side you need to handle all three cases as written in the link, i.e. `modifiedDate = b?.last_modified?[0] ?? DateTime.Now;`. – ckuri Oct 03 '18 at 00:41
  • @ckuri : This code perfectly works in 4.5 but gives error in 4.0, can you pls suggest its equivalent in 4.0 ? – Bokambo Oct 17 '18 at 17:38
  • 1
    In older .NET versions it would be `modifiedDate = b != null && b.last_modified != null && b.last_modified[0] != null ? b.last_modified[0].Value : DateTime.Now`. – ckuri Oct 17 '18 at 19:55

0 Answers0