I am trying to pull data from the table which has a DateTime data type with NULL values.
I am trying to get the required data by using the below method. However, it's throwing an error : ArgumentNullException: Value cannot be null. (Parameter 's')
TermDate = s.TermDate.HasValue ? s.TermDate : DateTime.Parse(s.TermDate.ToString().Replace(null, "-"))
Property: public DateTime? TermDate { get; set; }
Please advise.

Sam HobbsRank #107 · 20.5K reputationPosted Mar 5, 2024, 11:28 AM EST
You are checking
s.TermDatebut nots. The error message is saying that there is nos. You need to ensure thatsis notnull.Amit MohantyRank #112 · 20K reputationPosted Mar 6, 2024, 12:31 AM EST
You should check if s.TermDate is null before trying to access its value.
TermDate = s.TermDate.HasValue ? s.TermDate : (s.TermDate != null ? DateTime.Parse(s.TermDate.ToString().Replace(null, "-")) : (DateTime?)null);Naimish MakwanaRank #324 · 7.7K reputationPosted Mar 6, 2024, 2:41 AM EST
The issue here is that you’re trying to call
ToString()on anullvalue. Whens.TermDateisnull,s.TermDate.ToString()will throw anArgumentNullException.If you want to assign a default value when
s.TermDateisnull, you can do so directly in the ternary operator without callingToString()orReplace(). Here’s how you can do it:In this code, if
s.TermDatehas a value, it will be assigned toTermDate. Ifs.TermDateisnull, thenTermDatewill be assigned a default date (in this case, January 1, 1900). You can replacenew DateTime(1900, 1, 1)with any default date you prefer.Thanks
Rafnas T PRank #280 · 8.8K reputationPosted Mar 6, 2024, 4:33 AM EST
Hi,
You can try below code
string TermDate = s?.TermDate?.ToString()?? "-";
if termdate is null then string will display as - else will show the date.
Rohini ParadeRank #1,014 · 1.9K reputationPosted Mar 8, 2024, 6:41 AM EST
Here, Add null check for your object 's'. TermDate is null then provide any standard date according to business or
Jaimin ShethiyaRank #177 · 13.7K reputationPosted Mar 11, 2024, 2:19 AM EDT
Hello Satish,
Please try with the below statement.
TermDate = s.TermDate.HasValue ? s.TermDate : DateTime.Parse(Convert.ToString(s.TermDate).Replace(null, "-"))
Thanks