Edit: I don't believe this is a duplicate question as the question referenced explicitly states to test for null, as my code already does. But even with this test, the exception is thrown and I don't know why.
I've written code to parse through an API and after deserializing the response, I'm populating a class with the details. There's often null responses so null handling is a must. However after running for over 100,000 api calls, the program crashed complaining with NullReferenceException immediately after the string is tested for null. Whats going on here?
Condensed code:
class CsvFields
{
public string Twitter { get; set; }
public string Facebook { get; set; }
public string Youtube { get; set; }
public string Discord { get; set; }
public void New(BeamApiChannels Channel)
{
this.Twitter = Channel.user.social.twitter == null ? "" : CsvClean( Channel.user.social.twitter);
this.Facebook = Channel.user.social.facebook == null ? "" : CsvClean( Channel.user.social.facebook);
this.Youtube = Channel.user.social.youtube == null ? "" : CsvClean( Channel.user.social.youtube);
this.Discord = Channel.user.social.discord == null ? "" : CsvClean( Channel.user.social.discord);
}
public static string CsvClean(string str)
{
bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n"));
if (mustQuote)
{
StringBuilder sb = new StringBuilder();
foreach (char nextChar in str)
{
switch (nextChar)
{
case('"'):
sb.Append(nextChar);
sb.Append(nextChar);
break;
case ('\n'):
break;
case ('\r'):
break;
default:
sb.Append(nextChar);
break;
}
}
return sb.ToString();
}
}
}