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

I have code similar to this:

string s = CreateString();
if (s == "") foo(s);

If s is equal to "", call foo. If the string is null, which should never happen, then the NullReferenceException is fine (since this is, after all, an exception).

CodeAnalysis tells me to test s.IsNullOrEmpty. This would change functionality in several ways.

Performance is not a problem.

Is it safe to prevent the CA1820 warning associated with it?

Edit: Updated sample code and text to better reflect my case.

Edit: This is the (slightly modified) actual code (it is in the standard IXmlSerializable implementation):

public void ReadXml (XmlReader reader)
    // ...
    string img = reader.ReadElementString ("Image");
    if (img != "") {
        Image = Image.FromFile(img);
    }
    // ...
+3
8

- , , ; , NullReferenceException , , , , .

, :

static bool IsNullOrEmpty(this string value) {
    return string.IsNullOrEmpty(value);
}

:

if (s.IsNullOrEmpty()) foo();
+4

:

s "", foo. null, , NullReferenceException .

, CodeAnalysis:

if (s.Length == 0) foo(s);

:

CA1820?

, , , , . () , , .

+3

, , F1. , .

, , .

, " , ".

+2

:

if(s != null && s == "")

if

+1

, , . , .

, , . , . , . , void bool , , true/false.

+1

If zero is fine, you will be fine.

0
source

Yes.

But I would agree with CodeAnalysis with string.IsnullOrEmpty is a safe choice.

0
source

Do not handle the exception while you Can not gennerally is a bad idea, so the CA is right that you need to either handle null as empty or handle the exception. The null reference exception caused by using the return value is very bad. At least enter Debug.Assert (s! = Null) and compare with string.Empty

0
source

Source: https://habr.com/ru/post/1721691/


All Articles