How do you ignore a null statement, and only apply a method to remove special characters to only strings that are populated.
Answer1 = RemoveSpecialChars(doc.SelectSingleNode("/Main/Answer[@answerid='1']").Attributes["keypress"].Value);
Answer2 = RemoveSpecialChars(doc.SelectSingleNode("/Main/Answer[@answerid='2']").Attributes["keypress"].Value);
public string RemoveSpecialChars(string input)
{
return Regex.Replace(input, @"[^0-9a-zA-Z\._]", string.Empty);
}
What’s happening, is when the user presses and sends an answer one, and nothing for answer two I get an exception, because the method is trying to run on an empty string. What is the best way to pass answer1, if answer 2 is empty?
It sounds like your problem is not in the
RemoveSpecialCharsmethod, but rather in the return value ofSelectSingleNode(which may benull) or theAttributes["keypress"]attribute (which may also benull).Any of the above will result in a
NullReferenceException. Here’s rewritten code to guard against the first, which is probably causing the issue:Update:
To guard against a null
keypressattribute, you would doand the same for
Answer2.