You can either throw an exception if the parsing fails:
DateTime? dateOfService= null; if (string.IsNullOrEmpty(txtb_dateOfService.Text)) { dateOfService = null; } else {
or use an intermediate DateTime to save the result:
DateTime? dateOfService= null; if (string.IsNullOrEmpty(txtb_dateOfService.Text)) { dateOfService = null; } else { DateTime temp; if (DateTime.TryParse(txtb_dateOfService.Text, out temp)) { dateOfService = temp; } else { dateOfService = null; } }
Any of them can be logically simplified; I am showing a complete breakthrough to convey logic.
source share