>
>
>
V3022. Expression is always true/false.


V3022. Expression is always true/false.

The analyzer has detected a possible error that has to do with a condition which is always either true or false. Such conditions do not necessarily indicate a bug, but they need reviewing.

Consider the following example:

string niceUrl = GetUrl();
if (niceUrl != "#" || niceUrl != "") {
    Process(niceUrl);
} else {
    HandleError();
}

The analyzer outputs the following warning:

"V3022 Expression 'niceUrl != "#" || niceUrl != ""' is always true. Probably the '&&' operator should be used here. "

The else branch in this code will never be executed because regardless of what value the niceUrl variable refers to, one of the two comparisons with a string will always be true. To fix this error, we need to use operator && instead of ||. This is the fixed version of the code:

string niceUrl = GetUrl();
if (niceUrl != "#" && niceUrl != "") {
    Process(niceUrl);
} else {
    HandleError();
}

Now let's discuss a code sample with a meaningless comparison. It's not necessarily a bug, but this code should be reviewed:

byte type = reader.ReadByte();
if (type < 0)
    recordType = RecordType.DocumentEnd;
else
    recordType = GetRecordType(type);

The error here is in comparing an unsigned variable with zero. This sample will trigger the warning "V3022 Expression 'type < 0' is always false. Unsigned type value is always >= 0." The code either contains an unnecessary comparison or incorrectly handles the situation of reaching the end of the document.

The analyzer doesn't warn about every condition that is always true or false; it only diagnoses those cases when a bug is highly probable. Here are some examples of code that the analyzer treats as correct:

// 1) Code block temporarily not compiled
if (false && CheckCondition()) 
{
...
}

// 2) Expressions inside Debug.Assert()
public enum Actions { None, Start, Stop }
...
Debug.Assert(Actions.Start > 0);

This diagnostic is classified as:

You can look at examples of errors detected by the V3022 diagnostic.