Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I safely ignore CodeAnalysis warning: replace string == "" with string.IsNullOrEmpty?

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);
    }
    // ...
like image 592
mafu Avatar asked Dec 31 '25 18:12

mafu


1 Answers

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();
like image 67
Marc Gravell Avatar answered Jan 06 '26 17:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!