Ignore a null statement, apply method only to strings that are populated
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 happe开发者_如何学Goning, 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 RemoveSpecialChars
method, but rather in the return value of SelectSingleNode
(which may be null
) or the Attributes["keypress"]
attribute (which may also be null
).
Any of the above will result in a NullReferenceException
. Here's rewritten code to guard against the first, which is probably causing the issue:
var node1 = doc.SelectSingleNode("/Main/Answer[@answerid='1']");
var node2 = doc.SelectSingleNode("/Main/Answer[@answerid='2']");
Answer1 = node1 == null ? null : RemoveSpecialChars(node1.Attributes["keypress"].Value);
Answer2 = node2 == null ? null : RemoveSpecialChars(node2.Attributes["keypress"].Value);
Update:
To guard against a null keypress
attribute, you would do
Answer1 = node1 == null || node1.Attributes["keypress"] == null
? null
: RemoveSpecialChars(node1.Attributes["keypress"].Value);
and the same for Answer2
.
精彩评论