I've got code similar to this:
string s = CreateString();
if (s == "") foo(s);
If s equals "", foo should be called. If string is null, which should never happen, then a NullReferenceException is fine (as this is, after all, an exceptional situation).
CodeAnalysis tells me to test for s.IsNullOrEmpty. This would alter the functionality in a nunintended way.
Performance is not an issue.
Is it safe to suppress the associated CA1820 warning?
Edit: Updated code sample and text to better reflect my case.
Edit: This is the (slightly altered) actual code (it's in a standard IXmlSerializable implementation):
public void ReadXml (XmlReader reader)
// ...
string img = reader.ReadElementString ("Image");
if (img != "") {
Image = Image.FromFile(img);
}
// ...
It will behave differently with regards to nulls, so it depends what you want to happen; you mention that NullReferenceException would be OK, but there is nothing in the code cited that would raise this, hence why it could cause unexpected errors downstream.
I never have, but I'm always tempted to add:
static bool IsNullOrEmpty(this string value) {
return string.IsNullOrEmpty(value);
}
so I can use:
if (s.IsNullOrEmpty()) foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With