metrica
Мы используем куки, чтобы пользоваться сайтом было удобно.
Хорошо
to the top
close form

Заполните форму в два простых шага ниже:

Ваши контактные данные:

Шаг 1
Поздравляем! У вас есть промокод!

Тип желаемой лицензии:

Шаг 2
Team license
Enterprise license
** Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности
close form
Запросите информацию о ценах
Новая лицензия
Продление лицензии
--Выберите валюту--
USD
EUR
RUB
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
Бесплатная лицензия PVS‑Studio для специалистов Microsoft MVP
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
Для получения лицензии для вашего открытого
проекта заполните, пожалуйста, эту форму
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
Мне интересно попробовать плагин на:
* Нажимая на кнопку, вы даете согласие на обработку
своих персональных данных. См. Политику конфиденциальности

close form
check circle
Ваше сообщение отправлено.

Мы ответим вам на


Если вы так и не получили ответ, пожалуйста, проверьте папку
Spam/Junk и нажмите на письме кнопку "Не спам".
Так Вы не пропустите ответы от нашей команды.

Вебинар: Трудности при интеграции SAST, как с ними справляться - 04.04

>
>
>
Примеры ошибок, обнаруженных с помощью …

Примеры ошибок, обнаруженных с помощью диагностики V3022

V3022. Expression is always true/false.


Space-Station 14

V3022 Expression 'args.NeighborFreeTiles.Count == 0 && args.Neighbors.Count > 0 && component.SpreadAmount > 0' is always false. SmokeSystem.cs 128


private void OnSmokeSpread(....)
{
  if (.... || args.NeighborFreeTiles.Count == 0)
  {
     ....
     return;
  }
  ....
  if (args.NeighborFreeTiles.Count == 0 && ....) // <=
  {
    ....
  }
}

Space-Station 14

V3022. Expression is always true. Probably the '&&' operator should be used here. ....\Content.Shared\DoAfter\SharedDoAfterSystem.cs 49


private void OnStateChanged(...., MobStateChangedEvent args)
{
  if (   args.NewMobState != MobState.Dead
      || args.NewMobState != MobState.Critical) // <=
  {
    return;
  }
  ....
}

Space-Station 14

V3022. Expression 'f >= 0 || f <= 3000' is always true. Probably the '&&' operator should be used here. GasTankWindow.cs 168


public GasTankWindow(GasTankBoundUserInterface owner)
{
  ....
  _spbPressure = new FloatSpinBox
  {
    IsValid = f => f >= 0 || f <= 3000, // <=
    ....
  };
  ....
}

Barotrauma

V3022. Expression 'pathSteering != null' is always false. EnemyAIController.cs 1954


private void UpdateAttack(float deltaTime)
{
  ....
  if (pathSteering != null) // <= (line 1551)
  { .... }
  else
  {
    ....
    if (pathSteering != null) // <= (line 1954)
    {
      pathSteering.SteeringSeek(....);
    }
    else
    {
      SteeringManager.SteeringSeek(....);
    }
    ....
  }
  ....
}

Thrive

V3022. Expression 'random.Next(0, 1) == 1' is always false. MicrobeBenchmark.cs 520


private void SpawnMicrobe(Vector3 position)
{
  ....
  cloudSystem!.AddCloud(   random.Next(0, 1) == 1 // <=
                         ? phosphates
                         : ammonia,
                        ....);
}

Microsoft Code Contracts

V3022 Expression 'c > '\xFFFF'' is always false. Output.cs 685


private static string Encode(string s)
{
  ....
  foreach( char c in s ) {
    if (c == splitC || c == '\n' || c == '\\') {
      specialCount++;
    }
    else if (c > '\x7F') {
      if (c > '\xFFFF') specialCount += 9;
      else specialCount += 5;
    }
  }
  ....
}

ML.NET

V3022 Expression 'type == IntArrayType.Sparse' is always false. IntArray.cs 145


public static IntArray New(...., IntArrayType type, IntArrayBits bitsPerItem)
{
  ....
  Contracts.CheckParam(type == IntArrayType.Current ||
                       type == IntArrayType.Repeat ||
                       type == IntArrayType.Segmented, nameof(type));

  if (type == IntArrayType.Dense || bitsPerItem == IntArrayBits.Bits0)
  {
    ....
  }
  else if (type == IntArrayType.Sparse)
    return new DeltaSparseIntArray(length, bitsPerItem);
  ....
  return null;
}

.NET Core Libraries (CoreFX)

V3022 Expression 'readercount >= 0' is always true. Unsigned type value is always >= 0. ReaderWriterLockSlim.cs 977


private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
  ....
  uint readercount = GetNumReaders();
  ....

  if (readercount == 1 && _numWriteUpgradeWaiters > 0)
  {
    ....
  }
  else if (readercount == 0 && _numWriteWaiters > 0)
  {
    ExitMyLock();
    _writeEvent.Set();
  }
  else if (readercount >= 0)
  {
    ....
  }
  else
    ExitMyLock();
  ....
}

IronPython and IronRuby

V3022 Expression 'x < 0' is always false. Unsigned type value is always >= 0. IntOps.Generated.cs 1967


public static int __hash__(UInt64 x) {
  int total = unchecked((int) (((uint)x) + (uint)(x >> 32)));
  if (x < 0) {
    return unchecked(-total);
  }
  return total;
}

.NET Compiler Platform ("Roslyn")

V3022 Expression 'lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object' is always true. DkmClrValue.cs 136


public enum TypeCode
{
  ....
  Object = 1,
  ....
  DateTime = 16,
  ....
}

static object GetHostObjectValue(Type lmrType, object rawValue)
{
  var typeCode = Metadata.Type.GetTypeCode(lmrType);
  return (lmrType.IsPointer || lmrType.IsEnum ||
          typeCode != TypeCode.DateTime ||
          typeCode != TypeCode.Object)
            ? rawValue : null;
}

Sony ATF

V3022 Expression is always false. Atf.Gui.Wpf.vs2010 PriorityQuadTree.cs 575


public Rect Extent
{
    get { return _extent; }
    set
    {
        if (value.Top    < -1.7976931348623157E+308  ||
            value.Top    >  1.7976931348623157E+308  ||
            value.Left   < -1.7976931348623157E+308  ||
            value.Left   >  1.7976931348623157E+308  ||
            value.Width  >  1.7976931348623157E+308  ||
            value.Height >  1.7976931348623157E+308)
        {
            throw new ArgumentOutOfRangeException("value");
        }
        _extent = value;
        ReIndex();
    }
}

Space Engineers

V3022 Expression 'bagEntityId != null' is always true. Sandbox.Game MyCharacterInventorySpawnComponent.cs 60


private long SpawnInventoryContainer(
               MyDefinitionId bagDefinition)
{ ... }

public override void OnCharacterDead()
{
  ....
  var bagEntityId = SpawnInventoryContainer(
    Character.Definition.InventorySpawnContainerId.Value);
  if (bagEntityId != null)
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'info.WorkshopId == null' is always false. Sandbox.Game MyGuiBlueprintScreen.cs 326
  • V3022 Expression 'info.SteamIDOwner == null' is always false. Sandbox.Game MyGuiBlueprintScreen.cs 328
  • V3022 Expression 'result != null' is always true. Sandbox.Game MyGpsCollection.cs 293

Space Engineers

V3022 Expression 'i == 0' is always true. Sandbox.Game MyGridClipboardAdvanced.cs 790


private new bool TestPlacement()
{
  ....

  for (int i = 0; i < PreviewGrids.Count; ++i)
  {
    ....
    if (retval && i == 0)
    {
      ....
      var settings = i == 0 ?
        m_settings.GetGridPlacementSettings(grid, false) :
        MyPerGameSettings.BuildingSettings.SmallStaticGrid;
      ....
    }
  ....
  }
}

Similar errors can be found in some other places:

  • V3022 Expression 'i == 0 ? true : grid.IsStatic' is always true. Sandbox.Game MyGridClipboardAdvanced.cs 808
  • V3022 Expression 'i == 0' is always true. Sandbox.Game MyGridClipboardAdvanced.cs 808

Xenko

V3022 Expression 'moveNextFrame' is always true. SiliconStudio.Xenko.Engine AnimationChannel.cs 314


private void SetTime(CompressedTimeSpan timeSpan)
{
  ....
  while (....)
  {
    var moveNextFrame = currentKeyFrame.MoveNext();
    if (!moveNextFrame)
    {
      ....
      break;
    }
    var keyFrame = moveNextFrame ? currentKeyFrame.Current :
                                   data.ValueNext;
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'inputTexture.Dimension == TextureDimension.TextureCube' is always true. SiliconStudio.Xenko.Engine LambertianPrefilteringNoCompute.cs 66
  • V3022 Expression 'inputTexture.Dimension == TextureDimension.TextureCube' is always true. SiliconStudio.Xenko.Engine LambertianPrefilteringSH.cs 72

Xamarin.Forms

V3022 Expression 'genericParameter.Owner.GenericParameterType == GenericParameterType.Type' is always false. ICSharpCode.Decompiler TypesHierarchyHelpers.cs 441


public TypeReference ResolveWithContext(TypeReference type)
{
  ....
  if (genericParameter.Owner.GenericParameterType ==
        GenericParameterType.Type)
    return TypeArguments[genericParameter.Position];
  else
    return genericParameter.Owner.GenericParameterType
             == GenericParameterType.Type
           ? UnresolvedGenericTypeParameter :
             UnresolvedGenericMethodParameter;
  ....
}

Xamarin.Forms

V3022 Expression 'forceInferChildren' is always true. ICSharpCode.Decompiler TypeAnalysis.cs 632


TypeReference
DoInferTypeForExpression(
  ILExpression expr,
  TypeReference expectedType,
  bool forceInferChildren = false)
{
  ....
  if (forceInferChildren) {
    ....
    if (forceInferChildren) {
      InferTypeForExpression(
        expr.Arguments.Single(), lengthType);
    }
  }
  ....
}

WPF samples by Microsoft

V3022 Expression 'values != null' is always true. Util.cs 287


public static string FindNumeric(string content)
{
  string[] values = content.Split(' ');
  if (values != null)
  {
    return values[0];
  }
  return "none";
}

Accord.Net

V3022 Expression '(_i_inc < 0)' is always false. Accord.Math BoundedBroydenFletcherGoldfarbShanno.FORTRAN.cs 5222


private static void dscal(int n, double da, double[] dx,
                          int _dx_offset, int incx)
{
  ....
  if (((n <= 0) || (incx <= 0)))
  {
    return;
  }
  ....
  int _i_inc = incx;
  for (i = 1;
         (_i_inc < 0) ? i >= nincx : i <= nincx;
           i += _i_inc)
  ....
}

Old NASA World Wind (C#)

V3022 Expression 'this.linePoints != null' is always true. PathLine.cs 346


public override void Render(DrawArgs drawArgs)
{
  ....
  if(this.linePoints.Length > 1)    // <=
  {
    ....
    if(this.linePoints != null)     // <=
    {
      ....
    }
  }
  ....
}

Also see V3095


FlashDevelop

V3022 Expression 'setting == "GlobalClasspath"' is always false. PluginMain.cs 1194


private void SettingChanged(string setting)
{
  if (setting == "ExcludedFileTypes"
    || setting == "ExcludedDirectories"
    || setting == "ShowProjectClasspaths"
    || setting == "ShowGlobalClasspaths"
    || setting == "GlobalClasspath")
  {
    Tree.RebuildTree();
  }
  else if (setting == "ExecutableFileTypes")
  {
    FileInspector.ExecutableFileTypes =
    Settings.ExecutableFileTypes;
  }
  else if (setting == "GlobalClasspath") // <=
  {
    // clear compile cache for all projects
    FlexCompilerShell.Cleanup();
  }
}

Similar errors can be found in some other places:

  • V3022 Expression 'high == 0xBF' is always false. JapaneseContextAnalyser.cs 293
  • V3022 Expression '!Outline.FlagTestDrop' is always true. DockPanel.DockDragHandler.cs 769

Unity3D

V3022 Expression 'pointerEvent.pointerDrag != null' is always false. UnityEngine.UI TouchInputModule.cs 227


private void ProcessTouchPress(....)
{
  ....
  pointerEvent.pointerDrag = null;

  if (pointerEvent.pointerDrag != null)
      ExecuteEvents.Execute(pointerEvent.pointerDrag,
                            pointerEvent,
                            ExecuteEvents.endDragHandler);

  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'm_Peers == null' is always false. UnityEngine.Networking NetworkMigrationManager.cs 710
  • V3022 Expression 'uv2.gameObject == null' is always false. UnityEngine.Networking NetworkServer.cs 1731
  • V3022 Expression 'newEnterTarget != null' is always true. UnityEngine.UI BaseInputModule.cs 147

MSBuild

V3022 Expression 'itemsAndMetadataFound.Metadata.Values.Count > 0' is always true. Evaluator.cs 1752


private void EvaluateItemElement(....)
{
  ....
  if (itemsAndMetadataFound.Metadata != null &&
      itemsAndMetadataFound.Metadata.Values.Count > 0)
  {
    ....
    if (itemsAndMetadataFound.Metadata.Values.Count > 0)  // <=
    {
      needToProcessItemsIndividually = true;
    }
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'fixedPathInfo != null' is always true. FrameworkLocationHelper.cs 794
  • V3022 Expression '_shutdownException != null' is always false. InProcNode.cs 527
  • V3022 Expression 'proj != null' is always true. SolutionFile.cs 817
  • And 4 additional diagnostic messages.

GitExtensions

V3022 Expression '(lineLength > 0)' is always true. GitUI EditNetSpell.cs 807


public void EnsureEmptyLine(bool addBullet, int afterLine)
{
  ....
  if (lineLength > 0)
  {
    ....
    var newLine = (lineLength > 0) ?
                    Environment.NewLine :
                    String.Empty;
    ....
  }
}

Similar errors can be found in some other places:

  • V3022 Expression 'settings != null' is always true. GitUI HotkeySettingsManager.cs 62
  • V3022 Expression 'FileStatusListView.Items.Count > 0' is always true. GitUI FileStatusList.cs 688
  • V3022 Expression 'revisions.Count > 2' is always true. GitUI FormFormatPatch.cs 141
  • And 3 additional diagnostic messages.

PowerShell

V3022 Expression 'stateInfo.State == RunspacePoolState.Disconnected' is always false. System.Management.Automation RunspacePoolInternal.cs 581


public enum RunspacePoolState
{
  BeforeOpen = 0,
  Opening = 1,
  Opened = 2,
  Closed = 3,
  Closing = 4,
  Broken = 5,
  Disconnecting = 6,
  Disconnected = 7,
  Connecting = 8,
}

internal virtual int GetAvailableRunspaces()
{
  ....
  if (stateInfo.State == RunspacePoolState.Opened)
  {
    ....
    return (pool.Count + unUsedCapacity);
  }
  else if (stateInfo.State != RunspacePoolState.BeforeOpen &&
           stateInfo.State != RunspacePoolState.Opening)
  {
    throw new InvalidOperationException(
      HostInterfaceExceptionsStrings.RunspacePoolNotOpened);
  }
  else if (stateInfo.State == RunspacePoolState.Disconnected)
  {
    throw new InvalidOperationException(
      RunspacePoolStrings.CannotWhileDisconnected);
  }
  else
  {
    return maxPoolSz;
  }
  ....
}

Orchard CMS

V3022 Expression 'i == 4' is always false. WebHost.cs 162


public void Clean() {
  // Try to delete temporary files for up to ~1.2 seconds.
  for (int i = 0; i < 4; i++) {
    Log("Waiting 300msec before trying to delete ....");
    Thread.Sleep(300);

    if (TryDeleteTempFiles(i == 4)) {
      Log("Successfully deleted all ....");
      break;
    }
  }
}

Similar errors can be found in some other places:

  • V3022 Expression 'result == null' is always false. ContentFieldDriver.cs 175
  • V3022 Expression 'String.IsNullOrWhiteSpace(url)' is always true. GalleryController.cs 93
  • V3022 Expression '_smtpSettings.Host != null' is always true. SmtpMessageChannel.cs 143
  • And 8 additional diagnostic messages.

Umbraco

V3022 Expression 'name != "Min" || name != "Max"' is always true. Probably the '&&' operator should be used here. DynamicPublishedContentList.cs 415


private object Aggregate(....)
{
  ....
  if (name != "Min" || name != "Max")
  {
    throw new ArgumentException(
      "Can only use aggregate min or max methods on properties
       which are datetime");
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'macro == null' is always false. MacroController.cs 91
  • V3022 Expression 'p.Value == null' is always false. ImageCropperPropertyEditor.cs 216
  • V3022 Expression 'loginPageObj != null' is always true. ProtectPage.aspx.cs 93
  • And 7 additional diagnostic messages.

Umbraco

V3022 Expression '!stop' is always true. template.cs 229


public Control parseStringBuilder(....)
{
  ....
  bool stop = false;
  ....
  while (!stop)
  {
    ....
  }
  ....
}

Media Portal 2

V3022 Expression '"Invalid header name: " + name' is always not null. The operator '??' is excessive. HttpRequest.cs 309


public void AddHeader(string name, string value)
{
  if (string.IsNullOrEmpty(name))
    throw new BadRequestException(
      "Invalid header name: " + name ?? "<null>"); // <=
}

'+' operator has higher priority than operator '??'. So experssion '"Invalid header name: " + name' has been evaluated first.

Similar errors can be found in some other places:

  • V3022 Expression 'IsVignetteLoaded' is always false. TvdbFanartBanner.cs 219
  • V3022 Expression 'currentNumber == null && newNumber != null' is always false. MetadataUpdater.cs 375

PascalABC.NET

V3022 Expression 't == null' is always true. VisualPascalABCNET Debugger.cs 141


public static Type GetTypeForStatic(string name)
{
  Type t = stand_types[name] as Type;
  if (t != null) return t;
  if (t == null)  //  <=
    foreach (string s in ns_ht.Keys)
    {
      ....
    }
  t = PascalABCCompiler.NetHelper.NetHelper.FindType(name);
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'CodeCompletion.CodeCompletionController.CurrentParser == null' is always false. VisualPascalABCNET CodeCompletionKeyHandler.cs 91
  • V3022 Expression 'CodeCompletion.CodeCompletionController.CurrentParser == null' is always false. VisualPascalABCNET CodeCompletionKeyHandler.cs 114
  • V3022 Expression 'CodeCompletion.CodeCompletionController.CurrentParser == null' is always false. VisualPascalABCNET CodeCompletionKeyHandler.cs 136
  • And 7 additional diagnostic messages.

PascalABC.NET

V3022 [CWE-570] Expression 't != null' is always false. Visitor.cs 598


public void prepare_collection(....)
{
  myTreeNode t;
  ....
  if (t == null)
  {
    ....
    if (t != null)    // <=
      t.Nodes.Add(tn);
    else
      nodes.Add(tn);
    ....
  }
  ....
}

SubtitleEdit

V3022 CWE-570 Expression '_networkSession != null && _networkSession.LastSubtitle != null && i < _networkSession.LastSubtitle.Paragraphs.Count' is always false. Main.cs 7242


private void DeleteSelectedLines()
{
  ....
  if (_networkSession != null)                // <=
  {
    _networkSession.TimerStop();
    NetworkGetSendUpdates(indices, 0, null);
  }
  else
  {
    indices.Reverse();
    foreach (int i in indices)
    {
      _subtitle.Paragraphs.RemoveAt(i);
      if (_networkSession != null &&          // <=
          _networkSession.LastSubtitle != null &&
          i < _networkSession.LastSubtitle.Paragraphs.Count)
        _networkSession.LastSubtitle.Paragraphs.RemoveAt(i);
    }
  ....
  }
  ....
}

SubtitleEdit

V3022 CWE-570 Expression 'param.Bitmap.Width == 720 && param.Bitmap.Width == 480' is always false. Probably the '||' operator should be used here. ExportPngXml.cs 1808


private static string FormatFabTime(TimeCode time,
                                    MakeBitmapParameter param)
{
  if (param.Bitmap.Width == 720 && param.Bitmap.Width == 480)
    return $"....";

  // drop frame
  if (Math.Abs(param.... - 24 * (999 / 1000)) < 0.01 ||
      Math.Abs(param.... - 29 * (999 / 1000)) < 0.01 ||
      Math.Abs(param.... - 59 * (999 / 1000)) < 0.01)
      return $"....";

  return $"....";
}

SubtitleEdit

V3022 CWE-571 Expression 'listBoxVobFiles.Items.Count > 0' is always true. DvdSubRip.cs 533


private void DvdSubRip_Shown(object sender, EventArgs e)
{
  if (string.IsNullOrEmpty(_initialFileName))
    return;

  if (_initialFileName.EndsWith(".ifo", ....))
  {
    OpenIfoFile(_initialFileName);
  }
  else if (_initialFileName.EndsWith(".vob", ....))
  {
    listBoxVobFiles.Items.Add(_initialFileName);
    buttonStartRipping.Enabled = listBoxVobFiles.Items.Count > 0;
  }
  _initialFileName = null;
}

Unity C# reference source code

V3022 CWE-570 Expression 'index < 0 && index >= parameters.Length' is always false. AnimatorControllerPlayable.bindings.cs 287


public AnimatorControllerParameter GetParameter(int index)
{
  AnimatorControllerParameter[] param = parameters;
  if (index < 0 && index >= parameters.Length)
    throw new IndexOutOfRangeException(
      "Index must be between 0 and " + parameters.Length);
  return param[index];
}

Similar errors can be found in some other places:

  • V3022 CWE-570 Expression 'index < 0 && index >= parameters.Length' is always false. Animator.bindings.cs 711

Unity C# reference source code

V3022 CWE-570 Expression 'handle.valueIndex < 0 && handle.valueIndex >= list.Length' is always false. StyleSheet.cs 81


static T CheckAccess<T>(T[] list, StyleValueType type,
  StyleValueHandle handle)
{
  T value = default(T);
  if (handle.valueType != type)
  {
    Debug.LogErrorFormat(....  );
  }
  else if (handle.valueIndex < 0 &&
           handle.valueIndex >= list.Length)
  {
    Debug.LogError("Accessing invalid property");
  }
  else
  {
    value = list[handle.valueIndex];
  }
  return value;
}

Unity C# reference source code

V3022 CWE-571 Expression 'bRegisterAllDefinitions || (AudioSettings.GetSpatializerPluginName() == "GVR Audio Spatializer")' is always true. AudioExtensions.cs 463


// This is where we register our built-in spatializer extensions.
static private void RegisterBuiltinDefinitions()
{
  bool bRegisterAllDefinitions = true;

  if (!m_BuiltinDefinitionsRegistered)
  {
    if (bRegisterAllDefinitions ||
        (AudioSettings.GetSpatializerPluginName() ==
          "GVR Audio Spatializer"))
    {
    }

    if (bRegisterAllDefinitions ||
        (AudioSettings.GetAmbisonicDecoderPluginName() ==
          "GVR Audio Spatializer"))
    {
    }

    m_BuiltinDefinitionsRegistered = true;
  }
}

Similar errors can be found in some other places:

  • V3022 CWE-571 Expression 'bRegisterAllDefinitions || (AudioSettings.GetAmbisonicDecoderPluginName() == "GVR Audio Spatializer")' is always true. AudioExtensions.cs 467

Unity C# reference source code

V3022 CWE-570 Expression 'PerceptionRemotingPlugin.GetConnectionState() != HolographicStreamerConnectionState.Disconnected' is always false. HolographicEmulationWindow.cs 171


private void Disconnect()
{
  if (PerceptionRemotingPlugin.GetConnectionState() !=
      HolographicStreamerConnectionState.Disconnected)
    PerceptionRemotingPlugin.Disconnect();
}

internal static HolographicStreamerConnectionState
GetConnectionState()
{
  return HolographicStreamerConnectionState.Disconnected;
}

Unity C# reference source code

V3022 CWE-570 Expression 'PerceptionRemotingPlugin.GetConnectionState() == HolographicStreamerConnectionState.Connected' is always false. HolographicEmulationWindow.cs 177


private bool IsConnectedToRemoteDevice()
{
  return PerceptionRemotingPlugin.GetConnectionState() ==
         HolographicStreamerConnectionState.Connected;
}

internal static HolographicStreamerConnectionState
GetConnectionState()
{
  return HolographicStreamerConnectionState.Disconnected;
}

Infer.NET

V3022 Expression 'resultIndex == null' is always false. Compiler FactorManager.cs 382


internal static DependencyInformation GetDependencyInfo(....)
{
  ....
  IExpression resultIndex = null;
  ....
  if (resultIndex != null)
  {
    if (parameter.IsDefined(
          typeof(SkipIfMatchingIndexIsUniformAttribute), false))
    {
      if (resultIndex == null)
        throw new InferCompilerException(
                     parameter.Name
                   + " has SkipIfMatchingIndexIsUniformAttribute but "
                   + StringUtil.MethodNameToString(method)
                   + " has no resultIndex parameter");
      ....
     }
     ....
  }
  ....
}

Infer.NET

V3022 Expression 'genres.Length < 1 && genres.Length > 3' is always false. Probably the '||' operator should be used here. Evaluator Features.cs 242


public static Tuple<int, string> ComputeMovieGenre(int offset,
                                                   string feature)
{
  string[] genres = feature.Split('|');
  if (genres.Length < 1 && genres.Length > 3)
  {
    throw
      new ArgumentException(string.Format(
            "Movies should have between 1 and 3 genres; given {0}.",
            genres.Length));
  }

  double value = 1.0 / genres.Length;

  var result
    = new StringBuilder(
            string.Format(
              "{0}:{1}",
              offset + MovieGenreBuckets[genres[0]],
              value));

  for (int i = 1; i < genres.Length; ++i)
  {
    result.Append(
      string.Format(
        "|{0}:{1}",
        offset + MovieGenreBuckets[genres[i].Trim()],
        value));
  }

  return new Tuple<int, string>(MovieGenreBucketCount, result.ToString());
}

FastReport

V3022 Expression 'saveStreams' is always false. HTMLExport.cs 849


protected override void Finish()
{
  ....
  if (saveStreams)
  {
    FinishSaveStreams();
  }
  else
  {
    if (singlePage)
    {
      if (saveStreams)
      {
        int fileIndex = GeneratedFiles.IndexOf(singlePageFileName);
        DoPageEnd(generatedStreams[fileIndex]);
      }
      else { .... }
      ....
     }
     ....
  }
  ....
}

AWS SDK for .NET

V3022 [CWE-571] Expression 'doLog' is always true. AWSSDK.Core.Net45 StoredProfileAWSCredentials.cs 235


private static bool ValidCredentialsExistInSharedFile(....)
{
  ....
  var doLog = false;
  try
  {
    if (....)
    {
      return true;
    }
    else
    {
      doLog = true;
    }
  }
  catch (InvalidDataException)
  {
    doLog = true;
  }

  if (doLog)  // <=
  {
    ....
  }
  ....
}

AWS SDK for .NET

V3022 Expression '!result' is always false. AWSSDK.CognitoSync.PCL SQLiteLocalStorage.cs 353


public void PutValue(....)
{
  ....
  bool result = PutValueHelper(....);
  if (!result) <=
  {
    _logger.DebugFormat("{0}",
      @"Cognito Sync - SQLiteStorage - Put Value Failed");
  }
  else
  {
    UpdateLastModifiedTimestamp(....);
  }
  ....
}

private bool PutValueHelper(....)
{
  ....
  if (....))
  {
      return true;
  }

  if (record == null)
  {
    ....
    return true;
  }
  else
  {
    ....
    return true;
  }
}

.NET Core Libraries (CoreFX)

V3022 Expression 'names != null' is always true. DynamicDebuggerProxy.cs 426


private static IList<KeyValuePair<string, object>>
QueryDynamicObject(object obj)
{
  ....
  List<string> names = new List<string>(mo.GetDynamicMemberNames());
  names.Sort();
  if (names != null)
  { .... }
  ....
}

.NET Core Libraries (CoreFX)

V3022 Expression 'newLength == int.MaxValue' is always false. ObjectManager.cs 1423


private void EnlargeArray()
{
  int newLength = _values.Length * 2;
  if (newLength < 0)
  {
    if (newLength == int.MaxValue)
    {
      throw new SerializationException(SR.Serialization_TooManyElements);
    }
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'newLength == int.MaxValue' is always false. ObjectManager.cs 1511
  • V3022 Expression 'newLength == int.MaxValue' is always false. ObjectManager.cs 1558

.NET Core Libraries (CoreFX)

V3022 Expression '!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " "' is always true. OdbcCommandBuilder.cs 338


public string UnquoteIdentifier(....)
{
  ....
  if (!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " ")
    ....
  ....
}

.NET Core Libraries (CoreFX)

V3022 Expression 'cacheMemoryLimit != 0 && _memoryLimit != 0' is always false. CacheMemoryMonitor.cs 250


internal void SetLimit(int cacheMemoryLimitMegabytes)
{
  long cacheMemoryLimit = cacheMemoryLimitMegabytes;
  cacheMemoryLimit = cacheMemoryLimit << MEGABYTE_SHIFT;

  _memoryLimit = 0; // <=

  if (cacheMemoryLimit == 0 && _memoryLimit == 0)
    ....
  else if (cacheMemoryLimit != 0 && _memoryLimit != 0) // <=
    ....
  else if (cacheMemoryLimit != 0)
    ....
  ....
}

ShareX

V3022 [CWE-571] Expression 'dataObject != null' is always true. TaskThumbnailPanel.cs 415


private void PbThumbnail_MouseMove(object sender, MouseEventArgs e)
{
  ....
  IDataObject dataObject
    = new DataObject(DataFormats.FileDrop,
                     new string[] { Task.Info.FilePath });

  if (dataObject != null) // <=
  {
    Program.MainForm.AllowDrop = false;
    dragBoxFromMouseDown = Rectangle.Empty;
    pbThumbnail.DoDragDrop(dataObject,
        DragDropEffects.Copy | DragDropEffects.Move);
    Program.MainForm.AllowDrop = true;
  }
  ....
}

ShareX

V3022 [CWE-571] Expression 'img != null' is always true. ClipboardHelpers.cs 289


private static Image GetDIBImage(MemoryStream ms)
{
  ....
  try
  {
    ....
    return new Bitmap(bmp);
    ....
  }
  finally
  {
    if (gcHandle != IntPtr.Zero)
    {
      GCHandle.FromIntPtr(gcHandle).Free();
    }
  }
  ....
}
private static Image GetImageAlternative()
{
  ....
  using (MemoryStream ms = dataObject.GetData(format) as MemoryStream)
  {
    if (ms != null)
    {
      try
      {
        Image img = GetDIBImage(ms);
        if (img != null) // <=
        {
          return img;
        }
      }
      catch (Exception e)
      {
        DebugHelper.WriteException(e);
      }
    }
  }
  ....
}

ShareX

V3022 [CWE-571] Expression 'lvClipboardFormats.SelectedItems.Count > 0' is always true. AfterUploadForm.cs 155


private void btnCopyLink_Click(object sender, EventArgs e)
{
  ....
  if (lvClipboardFormats.SelectedItems.Count == 0)
  {
    url = lvClipboardFormats.Items[0].SubItems[1].Text;
  }
  else if (lvClipboardFormats.SelectedItems.Count > 0) // <=
  {
    url = lvClipboardFormats.SelectedItems[0].SubItems[1].Text;
  }
  ....
}

ShareX

V3022 Expression 'itemCount > 0' is always false. RegionCaptureForm.cs 1100


private void DrawCursorGraphics(Graphics g)
{
  ....
  int cursorOffsetX = 10, cursorOffsetY = 10, itemGap = 10, itemCount = 0;
  Size totalSize = Size.Empty;

  int magnifierPosition = 0;
  Bitmap magnifier = null;

  if (Options.ShowMagnifier)
  {
    if (itemCount > 0) totalSize.Height += itemGap; // <=
    ....
  }
  ....
}

Azure PowerShell

V3022 Expression 'apiType.HasValue' is always false. ApiManagementClient.cs 1134


private string GetApiTypeForImport(...., PsApiManagementApiType? apiType)
{
  ....
  if (apiType.HasValue)
  {
    switch(apiType.Value)
    {
      case PsApiManagementApiType.Http: return SoapApiType.SoapToRest;
      case PsApiManagementApiType.Soap: return SoapApiType.SoapPassThrough;
      default: return SoapApiType.SoapPassThrough;
    }
  }

  return apiType.HasValue ?        // <=
    apiType.Value.ToString("g") :
    PsApiManagementApiType.Http.ToString("g");
}

Azure PowerShell

V3022 Expression 'automationJob != null && automationJob == null' is always false. NodeConfigurationDeployment.cs 199


public NodeConfigurationDeployment(
  ....,
  Management.Automation.Models.Job automationJob = null,
  ....)
{
  ....
  if (automationJob != null && automationJob == null) return;
  ....
}

Azure PowerShell

V3022 Expression is always false. DataFactoryClient.Encrypt.cs 37


public virtual string OnPremisesEncryptString(....)
{
  ....
  if ( linkedServiceType == LinkedServiceType.OnPremisesSqlLinkedService
    && linkedServiceType == LinkedServiceType.OnPremisesOracleLinkedService
    && linkedServiceType == LinkedServiceType.OnPremisesFileSystemLinkedService
    && (value == null || value.Length == 0))
  {
    throw new ArgumentNullException("value");
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'Ekus == null' is always false. PSKeyVaultCertificatePolicy.cs 129

OpenCvSharp

V3022 Expression 'String.IsNullOrEmpty("winName")' is always false. Cv2_highgui.cs 46


public static void
DestroyWindow(string winName)
{
  if (String.IsNullOrEmpty("winName"))
    ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'string.IsNullOrEmpty("fileName")' is always false. FrameSource.cs 37
  • V3022 Expression 'string.IsNullOrEmpty("fileName")' is always false. FrameSource.cs 53

OpenCvSharp

V3022 Expression 'objectPoints == null' is always false. Cv2_calib3d.cs 1372


public static double CalibrateCamera(....)
{
  if (objectPoints == null)
    throw new ArgumentNullException(nameof(objectPoints));
  if (objectPoints == null)
    throw new ArgumentNullException(nameof(objectPoints));
  ....
}

Also see V3021

Similar errors can be found in some other places:

  • V3022 Expression 'objectPoints == null' is always false. Cv2_calib3d.cs 1446

OpenCvSharp

V3022 Expression 'label == MarkerValue' is always false. Labeller.cs 135


internal static class Labeller
{
  ....
  private const int MarkerValue = -1;
  public static int Perform(Mat img, CvBlobs blobs)
  {
    ....
    int label = 0;
    int lastLabel = 0;
    CvBlob lastBlob = null;

    for (int y = 0; y < h; y++)
    {
      for (int x = 0; x < w; x++)
      {
        if (imgIn[x + y * step] == 0)
          continue;

        bool labeled = labels[y, x] != 0;
        if (....)
        {
          labeled = true;

          // Label contour.
          label++;
          if (label == MarkerValue)    // <=
            throw new Exception();
          ....
        }
        ....
      }
      ....
    }
  }
}

AvaloniaUI

V3022 Expression is always true. Probably the '&&' operator should be used here. NavigationDirection.cs 89


public static bool IsDirectional(this NavigationDirection direction)
{
  return direction > NavigationDirection.Previous ||
         direction <= NavigationDirection.PageDown;
}

Emby

V3022 Expression 'processUnsupportedFrame(frame, CloseStatusCode.PolicyViolation, null)' is always false. WebSocket.cs 462


private bool processWebSocketFrame(WebSocketFrame frame)
{
  return frame.IsCompressed && _compression == CompressionMethod.None
         ? processUnsupportedFrame(....)
         : frame.IsFragmented
           ? processFragmentedFrame(frame)
           : frame.IsData
             ? processDataFrame(frame)
             : frame.IsPing
               ? processPingFrame(frame)
               : frame.IsPong
                 ? processPongFrame(frame)
                 : frame.IsClose
                   ? processCloseFrame(frame)
                   : processUnsupportedFrame(....);
}
private bool processUnsupportedFrame(....)
{
  processException(....);
  return false;
}
private bool processDataFrame(WebSocketFrame frame)
{
  ....
  return true;
}
private bool processPingFrame(WebSocketFrame frame)
{
  var mask = Mask.Unmask;
  return true;
}
private bool processPongFrame(WebSocketFrame frame)
{
  _receivePong.Set();
  return true;
}
private bool processCloseFrame(WebSocketFrame frame)
{
  var payload = frame.PayloadData;
  close(payload, !payload.ContainsReservedCloseStatusCode, false);
  return false;
}

Similar errors can be found in some other places:

  • V3022 Expression 'processCloseFrame(frame)' is always false. WebSocket.cs 461
  • V3022 Expression 'frame.IsClose ? processCloseFrame(frame) : processUnsupportedFrame(frame, CloseStatusCode.PolicyViolation, null)' is always false. WebSocket.cs 460
  • V3022 Expression 'processPongFrame(frame)' is always true. WebSocket.cs 459
  • And 3 additional diagnostic messages.

Chocolatey

V3022 [CWE-571] Expression 'shortPrompt' is always true. InteractivePrompt.cs 101


public static string
prompt_for_confirmation(.... bool shortPrompt = false, ....)
{
  ....
  if (shortPrompt)
  {
    var choicePrompt = choice.is_equal_to(defaultChoice) //1
    ?
    shortPrompt //2
    ?
    "[[{0}]{1}]".format_with(choice.Substring(0, 1).ToUpperInvariant(), //3
    choice.Substring(1,choice.Length - 1))
    :
    "[{0}]".format_with(choice.ToUpperInvariant()) //0
    :
    shortPrompt //4
    ?
    "[{0}]{1}".format_with(choice.Substring(0,1).ToUpperInvariant(), //5
    choice.Substring(1,choice.Length - 1))
    :
    choice; //0
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 [CWE-571] Expression 'shortPrompt' is always true. InteractivePrompt.cs 105

Chocolatey

V3022 [CWE-571] Expression 'installedPackageVersions.Count != 1' is always true. NugetService.cs 1405


private void remove_nuget_cache_for_package(....)
{
  if (!config.AllVersions && installedPackageVersions.Count > 1)
  {
    const string allVersionsChoice = "All versions";
    if (installedPackageVersions.Count != 1)
    {
      choices.Add(allVersionsChoice);
    }
    ....
  }
  ....
}

Nethermind

V3022 Expression 'missingParamsCount != 0' is always true. Nethermind.JsonRpc JsonRpcService.cs 127


if (missingParamsCount != 0)
{
  bool incorrectParametersCount = missingParamsCount != 0; // <=
  if (missingParamsCount > 0)
  {
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'i == 0' is always false. Nethermind.Synchronization BlockDownloader.cs 192

RavenDB

V3022 Expression 'dirpath == null' is always false. PosixHelper.cs(124) Voron


public static void EnsurePathExists(string file)
{
  var dirpath = Path.GetDirectoryName(file);
  List<string> dirsToCreate = new List<string>();
  while (Directory.Exists(dirpath) == false)
  {
    dirsToCreate.Add(dirpath);
    dirpath = Directory.GetParent(dirpath).ToString();
    if (dirpath == null)                                  // <=
      break;
  }
  dirsToCreate.ForEach(x => Directory.CreateDirectory(x));
}

RavenDB

V3022 Expression '_continuationState.Count > 0' is always true. ManualBlittableJsonDocumentBuilder.cs(152) Sparrow


public void WriteObjectEnd()
{
  ....
  if (_continuationState.Count > 1)
  {
    var outerState =
      _continuationState.Count > 0 ? _continuationState.Pop() : currentState;
    if (outerState.FirstWrite == -1)
      outerState.FirstWrite = start;
    _continuationState.Push(outerState);
  }
  ....
}

RavenDB

V3022 Expression 'command != null' is always true. AsyncDocumentSession.Load.cs(175) Raven.Client


public partial class AsyncDocumentSession
{
  ....
  private async Task LoadStartingWithInternal(....)
  {
    ....
    var command = operation.CreateRequest();
    if (command != null)                       // <=
    {
      await RequestExecutor
        .ExecuteAsync(command, Context, SessionInfo, token)
        .ConfigureAwait(false);

      if (stream != null)
        Context.Write(stream, command.Result.Results.Parent);
      else
        operation.SetResult(command.Result);
    }
    ....
  }
  ....
}

internal class LoadStartingWithOperation
{
  ....
  public GetDocumentsCommand CreateRequest()
  {
    _session.IncrementRequestCount();
    if (Logger.IsInfoEnabled)
      Logger.Info(....);

    return new GetDocumentsCommand(....);
  }
  ....
}

RavenDB

V3022 Expression 'GetCounterValueAndCheckIfShouldSkip(item.DocumentId, null, prop, out long value, out bool delete)' is always false. RavenEtlDocumentTransformer.cs(362) Raven.Server


private List<CounterOperation> GetCounterOperationsFor(RavenEtlItem item)
{
  ....
  for (var i = 0; i < counters.Count; i++)
  {
    counters.GetPropertyByIndex(i, ref prop);

    if (
      GetCounterValueAndCheckIfShouldSkip(
        item.DocumentId,
        null,
        prop,
        out long value,
        out bool delete
      )
    ) continue;
    ....
  }
  ....
}

private bool GetCounterValueAndCheckIfShouldSkip(
  LazyStringValue docId,
  string function,
  BlittableJsonReaderObject.PropertyDetails prop,
  out long value,
  out bool delete
)
{
  value = 0;

  if (prop.Value is LazyStringValue)
  {
    delete = true;
  }

  else
  {
    delete = false;
    value = CountersStorage.InternalGetCounterValue(
      prop.Value as BlittableJsonReaderObject.RawBlob,
      docId,
      prop.Name
    );

    if (function != null)
    {
      using (var result = BehaviorsScript.Run(
        Context,
        Context,
        function,
        new object[] { docId, prop.Name }
      ))
      {
        if (result.BooleanValue != true)
          return true;
      }
    }
  }

  return false;
}

RavenDB

V3022 Expression 'suspend.HasValue' is always true. RachisAdminHandler.cs(116) Raven.Server


public Task SuspendObserver()
{
  if (ServerStore.IsLeader())
  {
    var suspend = GetBoolValueQueryString("value");
    if (suspend.HasValue)                                  // <=
    {
      Server.ServerStore.Observer.Suspended = suspend.Value;
    }

    NoContentStatus();
    return Task.CompletedTask;
  }

  RedirectToLeader();

  return Task.CompletedTask;
}

protected bool? GetBoolValueQueryString(string name, bool required = true)
{
  var boolAsString = GetStringQueryString(name, required);
  if (boolAsString == null)
    return null;

  if (bool.TryParse(boolAsString, out bool result) == false)
    ThrowInvalidBoolean(name, boolAsString);

  return result;
}

protected string GetStringQueryString(string name, bool required = true)
{
  var val = HttpContext.Request.Query[name];
  if (val.Count == 0 || string.IsNullOrWhiteSpace(val[0]))
  {
    if (required)
      ThrowRequiredMember(name);

    return null;
  }

  return val[0];
}

private static void ThrowRequiredMember(string name)
{
  throw new ArgumentException(
    $"Query string {name} is mandatory, but wasn't specified."
  );
}

RavenDB

V3022 Expression 'me.Arguments.Count < 2 && me.Arguments.Count > 3' is always false. Probably the '||' operator should be used here. QueryMetadata.cs(861) Raven.Server


private OrderByField ExtractOrderByFromMethod(....)
{
  ....
  if (me.Arguments.Count < 2 && me.Arguments.Count > 3)
    throw new InvalidQueryException(....);
  ....
}

RavenDB

V3022 Expression is always true. Probably the '&&' operator should be used here. DeleteCertificateFromClusterCommand.cs(21) Raven.Server


public override void VerifyCanExecuteCommand(
  ServerStore store, TransactionOperationContext context, bool isClusterAdmin
)
{
  using (context.OpenReadTransaction())
  {
    var read = store.Cluster.GetCertificateByThumbprint(context, Name);
    if (read == null)
      return;

    var definition = JsonDeserializationServer.CertificateDefinition(read);
    if (
      definition.SecurityClearance != SecurityClearance.ClusterAdmin || // <=
      definition.SecurityClearance != SecurityClearance.ClusterNode     // <=
    )
      return;
  }

  AssertClusterAdmin(isClusterAdmin);
}

OpenRA

V3022 Expression 'Active' is always true. SupportPowerManager.cs 206


public virtual void Tick()
{
  ....

  Active = !Disabled && Instances.Any(i => !i.IsTraitPaused);
  if (!Active)
    return;

  if (Active)
  {
    ....
  }
}

OpenRA

V3022 Expression 'highlightStart > 0' is always true. LabelWithHighlightWidget.cs 54


Pair<string, bool>[] MakeComponents(string text)
{
  ....

  if (highlightStart > 0 && highlightEnd > highlightStart)  // <=
  {
    if (highlightStart > 0)                                 // <=
    {
      // Normal line segment before highlight
      var lineNormal = line.Substring(0, highlightStart);
      components.Add(Pair.New(lineNormal, false));
    }

    // Highlight line segment
    var lineHighlight = line.Substring(
      highlightStart + 1,
      highlightEnd - highlightStart – 1
    );
    components.Add(Pair.New(lineHighlight, true));
    line = line.Substring(highlightEnd + 1);
  }
  else
  {
    // Final normal line segment
    components.Add(Pair.New(line, false));
    break;
  }
  ....
}

OpenRA

V3022 Expression '!order.Queued && currentTransform.NextActivity != null' is always false. TransformsIntoTransforms.cs 44


void IResolveOrder.ResolveOrder(Actor self, Order order)
{
  ....
  if (!order.Queued || currentTransform == null)
    return;

  if (!order.Queued && currentTransform.NextActivity != null)
    currentTransform.NextActivity.Cancel(self);

  ....
}

OpenRA

V3022 Expression 'lobbyInfo == null' is always false. LobbyCommands.cs 851


public class LobbyCommands : ....
{
  ....
  static bool SyncLobby(....)
  {
    if (!client.IsAdmin)
    {
      server.SendOrderTo(conn, "Message", "Only the host can set lobby info");
      return true;
    }

    var lobbyInfo = Session.Deserialize(s);
    if (lobbyInfo == null)                    // <=
    {
      server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent");
      return true;
    }

    server.LobbyInfo = lobbyInfo;

    server.SyncLobbyInfo();

    return true;
  }
  ....
}

public class Session
{
  ....
  public static Session Deserialize(string data)
  {
    try
    {
      var session = new Session();
      ....
      return session;
    }
    catch (YamlException)
    {
      throw new YamlException(....);
    }
    catch (InvalidOperationException)
    {
      throw new YamlException(....);
    }
  }
  ....
}

OpenRA

V3022 Expression 'frameSlider != null' is always true. AssetBrowserLogic.cs 128


public class AssetBrowserLogic : ChromeLogic
{
  ....
  public AssetBrowserLogic(....)
  {
    ....
    frameSlider = panel.Get<SliderWidget>("FRAME_SLIDER");
    if (frameSlider != null)
    {
      ....
    }
    ....
  }
  ....
}

public abstract class Widget
{
  ....
  public T Get<T>(string id) where T : Widget
  {
    var t = GetOrNull<T>(id);
    if (t == null)
      throw new InvalidOperationException(
          "Widget {0} has no child {1} of type {2}".F(Id, id, typeof(T).Name));
    return t;
  }
  ....
}

Open XML SDK

V3022 Expression 'namespaceUri != null' is always true. OpenXmlElement.cs 497


public OpenXmlAttribute GetAttribute(string localName, string namespaceUri)
{
    ....
    if (namespaceUri == null)
    {
        // treat null string as empty.
        namespaceUri = string.Empty;
    }
    ....
    if (HasAttributes)
    {
        if (namespaceUri != null)  // <=
        {
            ....
        }
        ....
    }
    ....
}

Open XML SDK

V3022 Expression 'Complete()' is always false. ParticleCollection.cs 243


private bool IsComplete => Current is null ||
                           Current == _collection._element.FirstChild;

public bool MoveNext()
{
    ....
    if (IsComplete)
    {
        return Complete();
    }

    if (....)
    {
        return Complete();
    }

    return IsComplete ? Complete() : true;
}

Open XML SDK

V3022 Expression '_elementStack.Count > 0' is always true. OpenXmlDomReader.cs 501


private readonly Stack<OpenXmlElement> _elementStack;

private bool MoveToNextSibling()
{
    ....
    if (_elementStack.Count == 0)
    {
        _elementState = ElementState.EOF;
        return false;
    }
    ....
    if (_elementStack.Count > 0) // <=
    {
        _elementState = ElementState.End;
    }
    else
    {
        // no more element, EOF
        _elementState = ElementState.EOF;
    }
    ....
}

Open XML SDK

V3022 Expression 'rootElement == null' is always false. OpenXmlPartReader.cs 746


private static OpenXmlElement CreateElement(string namespaceUri, string name)
{
    if (string.IsNullOrEmpty(name))
    {
        throw new ArgumentException(....);
    }

    if (NamespaceIdMap.TryGetNamespaceId(namespaceUri, out byte nsId)
        && ElementLookup.Parts.Create(nsId, name) is OpenXmlElement element)
    {
        return element;
    }

    return new OpenXmlUnknownElement();
}

private bool ReadRoot()
{
  ....
  var rootElement = CreateElement(....);

  if (rootElement == null) // <=
  {
      throw new InvalidDataException(....);
  }
  ....
}

Open XML SDK

V3022 Expression 'nameProvider' is always not null. The operator '?.' is excessive. OpenXmlSimpleTypeExtensions.cs 50


public static XmlQualifiedName GetSimpleTypeQualifiedName(....)
{
    foreach (var validator in validators)
    {
        if (validator is INameProvider nameProvider &&
            nameProvider?.QName is XmlQualifiedName qname) // <=
        {
            return qname;
        }
    }

    return type.GetSimpleTypeQualifiedName();
}

Open XML SDK

V3022 Expression 'extension == ".xlsx" || extension == ".xlsm"' is always false. PresentationDocument.cs 246


public static PresentationDocument CreateFromTemplate(string path)
{
    ....
    string extension = Path.GetExtension(path);
    if (extension != ".pptx" && extension != ".pptm" &&
        extension != ".potx" && extension != ".potm")
    {
        throw new ArgumentException("...." + path, nameof(path));
    }

    using (PresentationDocument template = PresentationDocument.Open(....)
    {
        PresentationDocument document = (PresentationDocument)template.Clone();

        if (extension == ".xlsx" || extension == ".xlsm")
        {
            return document;
        }
        ....
    }
    ....
}

Open XML SDK

V3022 Expression 'OpenSettings.MarkupCompatibilityProcessSettings == null' is always false. OpenXmlPackage.cs 661


public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
    get
    {
        if (_mcSettings is null)
        {
            _mcSettings = new MarkupCompatibilityProcessSettings(....);
        }

        return _mcSettings;
    }

    set
    {
        _mcSettings = value;
    }
}

public MarkupCompatibilityProcessSettings MarkupCompatibilityProcessSettings
{
    get
    {
        if (OpenSettings.MarkupCompatibilityProcessSettings == null) // <=
        {
            return new MarkupCompatibilityProcessSettings(....);
        }
        else
        {
            return OpenSettings.MarkupCompatibilityProcessSettings;
        }
    }
}

QuantConnect Lean

V3022 Expression '_random.Next(0, 1) == 0' is always true. RandomValueGenerator.cs 142


public virtual DateTime NextDate(....)
{
  ....
  // both are valid dates, so chose one randomly
  if (   IsWithinRange(nextDayOfWeek, minDateTime, maxDateTime)
      && IsWithinRange(previousDayOfWeek, minDateTime, maxDateTime))
  {
    return _random.Next(0, 1) == 0  // <=
           ? previousDayOfWeek
           : nextDayOfWeek;
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'symbol.SecurityType != SecurityType.Equity || resolution != Resolution.Daily || resolution != Resolution.Hour' is always true. LiveTradingDataFeedTests.cs 1431
  • V3022 Expression 'request.Parameters.Count > 0' is always true. GDAXBrokerage.Utility.cs 63

ONLYOFFICE Community Server

V3022 Expression 'string.IsNullOrEmpty("password")' is always false. SmtpSettings.cs 104


public void SetCredentials(string userName, string password, string domain)
{
    if (string.IsNullOrEmpty(userName))
    {
        throw new ArgumentException("Empty user name.", "userName");
    }
    if (string.IsNullOrEmpty("password"))
    {
        throw new ArgumentException("Empty password.", "password");
    }
    CredentialsUserName = userName;
    CredentialsUserPassword = password;
    CredentialsDomain = domain;
}

ONLYOFFICE Community Server

V3022 Expression 'String.IsNullOrEmpty("name")' is always false. SendInterceptorSkeleton.cs 36


public SendInterceptorSkeleton(
  string name,                                                  // <=
  ....,
  Func<NotifyRequest, InterceptorPlace, bool> sendInterceptor)
{
    if (String.IsNullOrEmpty("name"))                           // <=
        throw new ArgumentNullException("name");
    if (String.IsNullOrEmpty("sendInterceptor"))
        throw new ArgumentNullException("sendInterceptor");

    method = sendInterceptor;
    Name = name;
    PreventPlace = preventPlace;
    Lifetime = lifetime;
}

Similar errors can be found in some other places:

  • V3022 Expression 'String.IsNullOrEmpty("sendInterceptor")' is always false. SendInterceptorSkeleton.cs 37

ONLYOFFICE Community Server

V3022 Expression 'id < 0' is always false. Unsigned type value is always >= 0. UserFolderEngine.cs 173


public MailUserFolderData Update(uint id, string name, uint? parentId = null)
{
    if (id < 0)
        throw new ArgumentException("id");
    ....
}

ONLYOFFICE Community Server

V3022 Expression 'portalUser.BirthDate.ToString()' is always not null. The operator '??' is excessive. LdapUserManager.cs 436


public DateTime? BirthDate { get; set; }

private bool NeedUpdateUser(UserInfo portalUser, UserInfo ldapUser)
{
  ....
  _log.DebugFormat("NeedUpdateUser by BirthDate -> portal: '{0}', ldap: '{1}'",
      portalUser.BirthDate.ToString() ?? "NULL",  // <=
      ldapUser.BirthDate.ToString() ?? "NULL");   // <=
  needUpdate = true;
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'ldapUser.BirthDate.ToString()' is always not null. The operator '??' is excessive. LdapUserManager.cs 437
  • V3022 Expression 'portalUser.Sex.ToString()' is always not null. The operator '??' is excessive. LdapUserManager.cs 444
  • V3022 Expression 'ldapUser.Sex.ToString()' is always not null. The operator '??' is excessive. LdapUserManager.cs 445

ONLYOFFICE Community Server

V3022 Expression is always true. Probably the '&&' operator should be used here. ListItemHistoryDao.cs 140


public virtual int CreateItem(ListItemHistory item)
{
    if (item.EntityType != EntityType.Opportunity ||   // <=
        item.EntityType != EntityType.Contact)
        throw new ArgumentException();

    if (item.EntityType == EntityType.Opportunity &&
        (DaoFactory.DealDao.GetByID(item.EntityID) == null ||
         DaoFactory.DealMilestoneDao.GetByID(item.StatusID) == null))
        throw new ArgumentException();

    if (item.EntityType == EntityType.Contact &&
        (DaoFactory.ContactDao.GetByID(item.EntityID) == null ||
         DaoFactory.ListItemDao.GetByID(item.StatusID) == null))
        throw new ArgumentException();
    ....
}

ILSpy

V3022 Expression 'pt != null' is always true. ICSharpCode.Decompiler FunctionPointerType.cs 168


public override IType VisitChildren(TypeVisitor visitor)
{
  ....
  IType[] pt = (r != ReturnType) ? new IType[ParameterTypes.Length] : null;
  ....
  if (pt == null)
    return this;
  else
    return new FunctionPointerType(
      module, CallingConvention, CustomCallingConventions,
      r, ReturnIsRefReadOnly,
      pt != null ? pt.ToImmutableArray() : ParameterTypes,    // <=
      ParameterReferenceKinds);
}

ILSpy

V3022 Expression 'settings.LoadInMemory' is always true. ICSharpCode.Decompiler CSharpDecompiler.cs 394


static PEFile LoadPEFile(string fileName, DecompilerSettings settings)
{
  settings.LoadInMemory = true;
  return new PEFile(
    fileName,
    new FileStream(fileName, FileMode.Open, FileAccess.Read),
    streamOptions: settings.LoadInMemory ?                           // <=
      PEStreamOptions.PrefetchEntireImage : PEStreamOptions.Default,
    metadataOptions: settings.ApplyWindowsRuntimeProjections ?
        MetadataReaderOptions.ApplyWindowsRuntimeProjections :
        MetadataReaderOptions.None
  );
}

public bool LoadInMemory {
  get { return loadInMemory; }
  set {
      if (loadInMemory != value)
      {
        loadInMemory = value;
        OnPropertyChanged();
      }
  }
}

ILSpy

V3022 Expression 'ta' is always not null. The operator '??' is excessive. ICSharpCode.Decompiler ParameterizedType.cs 354


public IType VisitChildren(TypeVisitor visitor)
{
  ....
  if (ta == null)
      return this;
  else
      return new ParameterizedType(g, ta ?? typeArguments);     // <=
}

ILSpy

V3022 Expression 'negatedOp == BinaryOperatorType.Any' is always true. ICSharpCode.Decompiler CSharpUtil.cs 79


static Expression InvertConditionInternal(Expression condition)
{
  var bOp = (BinaryOperatorExpression)condition;

  if (   (bOp.Operator == BinaryOperatorType.ConditionalAnd)
      || (bOp.Operator == BinaryOperatorType.ConditionalOr))
  {
    ....
  }
  else if (   (bOp.Operator == BinaryOperatorType.Equality)
           || (bOp.Operator == BinaryOperatorType.InEquality)
           || (bOp.Operator == BinaryOperatorType.GreaterThan)
           || (bOp.Operator == BinaryOperatorType.GreaterThanOrEqual)
           || (bOp.Operator == BinaryOperatorType.LessThan)
           || (bOp.Operator == BinaryOperatorType.LessThanOrEqual))
  {
    ....
  }
  else
  {
    var negatedOp = NegateRelationalOperator(bOp.Operator);
    if (negatedOp == BinaryOperatorType.Any)                  // <=
      return new UnaryOperatorExpression(....);
    bOp = (BinaryOperatorExpression)bOp.Clone();
    bOp.Operator = negatedOp;
    return bOp;
  }
}

public static BinaryOperatorType NegateRelationalOperator(BinaryOperatorType op)
{
  switch (op)
  {
    case BinaryOperatorType.GreaterThan:
      return BinaryOperatorType.LessThanOrEqual;
    case BinaryOperatorType.GreaterThanOrEqual:
      return BinaryOperatorType.LessThan;
    case BinaryOperatorType.Equality:
      return BinaryOperatorType.InEquality;
    case BinaryOperatorType.InEquality:
      return BinaryOperatorType.Equality;
    case BinaryOperatorType.LessThan:
      return BinaryOperatorType.GreaterThanOrEqual;
    case BinaryOperatorType.LessThanOrEqual:
      return BinaryOperatorType.GreaterThan;
    case BinaryOperatorType.ConditionalOr:
      return BinaryOperatorType.ConditionalAnd;
    case BinaryOperatorType.ConditionalAnd:
      return BinaryOperatorType.ConditionalOr;
  }
  return BinaryOperatorType.Any;
}

EFCore

V3022 Expression 'setTargetAsPrincipal.Value' is always true. EFCore InternalEntityTypeBuilder.cs 2747


private InternalForeignKeyBuilder? HasRelationship(....,
                                                   bool? setTargetAsPrincipal,
                                                   ....)
{
  ....
  var navigationProperty = navigationToTarget?.MemberInfo;

  if (setTargetAsPrincipal == false || ....)                // <=
  {
      return ....
  }

  if (   configurationSource == ConfigurationSource.Explicit
      && setTargetAsPrincipal.HasValue)                     // <=
  {
      if (setTargetAsPrincipal.Value)                       // <=
      {
        ....
        throw new InvalidOperationException(....); // Exception 1
      }
      else
      {
        ....
        throw new InvalidOperationException(....); //Exception 2
      }
  }
  ....
}

EFCore

V3022 Expression 'columnName == null' is always false. EFCore.Relational RelationalModel.cs 244


private static void AddDefaultMappings(....)
{
  ....
  foreach (var property in entityType.GetProperties())
  {
    var columnName = property.GetColumnBaseName();
    if (columnName == null)
    {
      continue;
    }
    ....
  }
  ....
}

public static string GetColumnBaseName(....)
  =>    (string?)property.FindAnnotation(....)?.Value
     ?? property.GetDefaultColumnBaseName();

public static string GetDefaultColumnBaseName(....)
  => Uniquifier.Truncate(property.Name,
                         property.DeclaringEntityType
                                 .Model
                                 .GetMaxIdentifierLength());

public static string Truncate(....)
{
  ....
  var builder = new StringBuilder();
  ....
  return builder.ToString();
}

Ryujinx

V3022 Expression 'result != KernelResult.Success' is always false. KMemoryRegionManager.cs 169


private KernelResult AllocatePagesImpl(....)
{
    ....
    KernelResult result = pageList.AddRange(address, blockPagesCount);

    if (result != KernelResult.Success)
    ....
}

public KernelResult AddRange(....)
{
    ....
    return KernelResult.Success;
}

Ryujinx

V3022 Expression 'Base == null' is always false. Demangler.cs 2049


private BaseNode ParseExpression()
{
    ....
    BaseNode Base = ParseExpression();
    if (Base == null)
    {
        return null;
    }

    BaseNode subscript = ParseExpression();
    if (Base == null)
    {
        return null;
    }
    ....
}

Description V3021 There are two 'if' statements with identical conditional expressions. The first 'if' statement contains method return. This means that the second 'if' statement is senseless Demangler.cs 2043


Ryujinx

V3022 Expression 'mainNca != null' is always true. ApplicationLoader.cs 272


public void LoadNsp(string nspFile)
{
    ....
    if (mainNca == null)
    {
        Logger.Error?.Print(LogClass.Loader,
            "Unable to load NSP: Could not find Main NCA");

        return;
    }

    if (mainNca != null)
    {
        _device.Configuration.ContentManager.ClearAocData();
        _device.Configuration.ContentManager.AddAocData(nsp,
            nspFile,
            mainNca.Header.TitleId,
            _device.Configuration.FsIntegrityCheckLevel);

        LoadNca(mainNca, patchNca, controlNca);

        return;
    }

    // This is not a normal NSP, it's actually a ExeFS as a NSP
    LoadExeFs(nsp);
}

Description V3142 Unreachable code detected. It is possible that an error is present. ApplicationLoader.cs 283

Similar errors can be found in some other places:

  • V3022 Expression 'result == null' is always false. Demangler.cs 2937

Ryujinx

V3022 Expression 'result == null' is always false. Demangler.cs 2906


private BaseNode ParseUnresolvedName(....)
{
    ....
    BaseNode qualifier = ParseSimpleId();
    if (qualifier == null)
    {
        return null;
    }
    if (result != null)
    {
        result = new QualifiedName(result, qualifier);
    }
    else if (isGlobal)
    {
        result = new GlobalQualifiedName(qualifier);
    }
    else
    {
        result = qualifier;
    }

    if (result == null)
    {
        return null;
    }
    ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'result == null' is always false. Demangler.cs 2848
  • V3022 Expression 'result == null' is always false. Demangler.cs 3094
  • V3022 Expression 'result == null' is always false. Demangler.cs 2930

PeachPie

V3022 Expression '!Core.Convert.TryParseDigits(s, ref pos, false, out value, out numDigits)' is always false. DateTimeParsing.cs 1440


internal static bool TryParseIso8601Duration(string str,
                                             out DateInfo result,
                                             out bool negative)
{
  ....
  if (pos >= length) goto InvalidFormat;

  if (s[pos++] != 'P') goto InvalidFormat;

  if (!Core.Convert.TryParseDigits(....))
    goto Error;

  if (pos >= length) goto InvalidFormat;

  if (s[pos] == 'Y')
  {
    ....

    if (!Core.Convert.TryParseDigits(....))
      goto Error;

    if (pos >= length) goto InvalidFormat;
  }
  ....
  InvalidFormat:
  Error:

    result = default;
    negative = default;
    return false;
}

PeachPie

V3022 Expression 'node != null' is always true. Datastructures.cs 432


public PhpValue offsetGet(PhpValue offset)
{
  var node = GetNodeAtIndex(offset);

  Debug.Assert(node != null);

  if (node != null)          // <=
    return node.Value;
  else
    return PhpValue.Null;
}

private LinkedListNode<PhpValue> GetNodeAtIndex(PhpValue index)
{
  return GetNodeAtIndex(GetValidIndex(index));
}

private LinkedListNode<PhpValue> GetNodeAtIndex(long index)
{
  var node = _baseList.First;
  while (index-- > 0 && node != null)
  {
    node = node.Next;
  }

  return node ?? throw new OutOfRangeException();
}

PeachPie

V3022 Expression 'wrapperClass == null' is always false. Streams.cs 555


public static bool stream_wrapper_register(....)
{
  // check if the scheme is already registered:
  if (   string.IsNullOrEmpty(protocol)
      || StreamWrapper.GetWrapperInternal(ctx, protocol) == null)
  {
    // TODO: Warning?
    return false;
  }

  var wrapperClass = ctx.GetDeclaredTypeOrThrow(classname, true);
  if (wrapperClass == null) // <=
  {
    return false;
  }

  ....
}

PhpTypeInfo GetDeclaredTypeOrThrow(string name, bool autoload = false)
{
  return GetDeclaredType(name, autoload) ??
         throw PhpException.ClassNotFoundException(name);
}

PeachPie

V3022 Expression 'haveskipped != offset' is always true. Streams.cs 769


public static int stream_copy_to_stream(...., int offset = 0)
{
  ....
  if (offset > 0)
  {
    int haveskipped = 0;

    while (haveskipped != offset)  // <=
    {
      TextElement data;

      int toskip = offset - haveskipped;
      if (toskip > from.GetNextDataLength())
      {
        data = from.ReadMaximumData();
        if (data.IsNull) break;
      }
      else
      {
        data = from.ReadData(toskip, false);
        if (data.IsNull) break; // EOF or error.
        Debug.Assert(data.Length <= toskip);
      }

      Debug.Assert(haveskipped <= offset);
    }
  }
  ....
}

PeachPie

V3022 Expression 'string.Join(", ", h.Value)' is always not null. The operator '??' is excessive. Web.cs 932


public static PhpArray getallheaders(Context ctx)
{
  var webctx = ctx.HttpPhpContext;
  if (webctx != null)
  {
    var headers = webctx.RequestHeaders;
    if (headers != null)
    {
      var result = new PhpArray(16);

      foreach (var h in headers)
      {
        result[h.Key] = string.Join(", ", h.Value) ?? string.Empty;
      }

      return result;
    }
  }

  return null;
}

LINQ to DB

V3022 Expression 'version > 15' is always true. SqlServerTools.cs 250


internal static IDataProvider? ProviderDetector(IConnectionStringSettings css,
  string connectionString)
{
  ....
  if (int.TryParse(conn.ServerVersion.Split('.')[0], out var version))
  {
    if (version <= 8)
      return GetDataProvider(SqlServerVersion.v2000, provider);

    using (var cmd = conn.CreateCommand())
    {
      ....
      switch (version)
      {
        case  8 : return GetDataProvider(SqlServerVersion.v2000, provider);
        case  9 : return GetDataProvider(SqlServerVersion.v2005, provider);
        case 10 : return GetDataProvider(SqlServerVersion.v2008, provider);
        case 11 :
        case 12 : return GetDataProvider(SqlServerVersion.v2012, provider);
        case 13 : return GetDataProvider(SqlServerVersion.v2016, provider);
        case 14 :
        case 15 : return GetDataProvider(SqlServerVersion.v2017, provider);
        default :
          if (version > 15)
            return GetDataProvider(SqlServerVersion.v2017, provider);
          return GetDataProvider(SqlServerVersion.v2008, provider);
      }
    }
  }
  ....
}

LINQ to DB

V3022 Expression 'table == null' is always true. LoadWithBuilder.cs 113


TableBuilder.TableContext GetTableContext(IBuildContext ctx, Expression path,
  out Expression? stopExpression)
{
  stopExpression = null;

  var table = ctx as TableBuilder.TableContext;

  if (table != null)
    return table;

  if (ctx is LoadWithContext lwCtx)
    return lwCtx.TableContext;

  if (table == null)
  {
    ....
  }
  ....
}

Similar errors can be found in some other places:

  • V3022 Expression 'output.OutputItems.Count > 0' is always false. SqlServerSqlBuilder.cs 114
  • V3022 Expression 'sqlExpression == null' is always false. AggregationBuilder.cs 74
  • V3022 Expression 'table == null' is always true. SequenceHelper.cs 38
  • And 14 additional diagnostic messages.

LINQ to DB

V3022 Expression 'rows' is always not null. The operator '?.' is excessive. SQLiteSqlBuilder.cs 214


protected override void BuildSqlValuesTable(
  SqlValuesTable valuesTable,
  string alias,
  out bool aliasBuilt)
{
  valuesTable = ConvertElement(valuesTable);
  var rows = valuesTable.BuildRows(OptimizationContext.Context);

  if (rows.Count == 0)
  {
    ....
  }
  else
  {
    ....

    if (rows?.Count > 0)
    {
     ....
    }

    ....
  }
  aliasBuilt = false;
}

DotNetNuke

V3022 Expression 'pageIndex < 0' is always false. ListModules.cs 61


public int Page { get; set; } = 1;
public override IConsoleResultModel Run()
{
  ....
  var pageIndex = (this.Page > 0 ? this.Page - 1 : 0);
  pageIndex = pageIndex < 0 ? 0 : pageIndex;
  ....
}

DotNetNuke

V3022 Expression 'portalKeys.Count > 0' is always false. CacheController.cs 968


private CacheDependency GetTabsCacheDependency(IEnumerable<int> portalIds)
{
  ....
  // get the portals list dependency
  var portalKeys = new List<string>();
  if (portalKeys.Count > 0)
  {
    keys.AddRange(portalKeys);
  }
  ....
}

DotNetNuke

V3022 Expression 'xDoc != null' is always true. JournalEntity.cs 30


public JournalEntity(string entityXML)
{
  ....
  XmlDocument xDoc = new XmlDocument { XmlResolver = null };
  xDoc.LoadXml(entityXML);
  if (xDoc != null)
  ....
}

DotNetNuke

V3022 Expression is always true. Probably the '&&' operator should be used here. AdvancedUrlRewriter.cs 1695


public enum ActionType
{
  ....
  Redirect302Now = 2,
  ....
  Redirect302 = 5,
  ....
}

public ActionType Action { get; set; }

private static bool CheckForRedirects(....)
{
  ....
  if (   result.Action != ActionType.Redirect302Now
      || result.Action != ActionType.Redirect302)
  ....
}

DotNetNuke

V3022 Expression 'url == null' is always false. MvcRoutingManager.cs 66


public Route MapRoute(string moduleFolderName,
                      string routeName,
                      string url,
                      object defaults,
                      object constraints,
                      string[] namespaces)
{
  if (   namespaces == null
      || namespaces.Length == 0
      || string.IsNullOrEmpty(namespaces[0]))
  {
    throw new ArgumentException(Localization.GetExceptionMessage(
      "ArgumentCannotBeNullOrEmpty",
      "The argument '{0}' cannot be null or empty.",
      "namespaces"));
  }

  Requires.NotNullOrEmpty("moduleFolderName", moduleFolderName);

  url = url.Trim('/', '\\');

  var prefixCounts = this.portalAliasMvcRouteManager.GetRoutePrefixCounts();
  Route route = null;

  if (url == null)
  {
    throw new ArgumentNullException(nameof(url));
  }
  ....
}

DotNetNuke

V3022 Expression 'y < 0' is always false. Unsigned type value is always >= 0. CountryLookup.cs 210


public int SeekCountry(int offset, long ipNum, short depth)
{
  ....
  var buffer = new byte[6];
  byte y;

  ....
  if (y < 0)
  {
    y = Convert.ToByte(y + 256);
  }

  ....
}

Umbraco

V3022 Expression 'pageNumber > 0' is always true. EntityController.cs 625


public ActionResult<PagedResult<EntityBasic>> GetPagedChildren(....
                                                               int pageNumber,
                                                               ....)
{
  if (pageNumber <= 0)
  {
    return NotFound();
  }
  ....
  if (objectType.HasValue)
  {
    if (id == Constants.System.Root &&
        startNodes.Length > 0 &&
        startNodes.Contains(Constants.System.Root) == false &&
        !ignoreUserStartNodes)
    {
      if (pageNumber > 0)  // <=
      {
        return new PagedResult<EntityBasic>(0, 0, 0);
      }
      IEntitySlim[] nodes = _entityService.GetAll(objectType.Value,
                                                  startNodes).ToArray();
      if (nodes.Length == 0)
      {
        return new PagedResult<EntityBasic>(0, 0, 0);
      }

      if (pageSize < nodes.Length)
      {
        pageSize = nodes.Length; // bah
      }

      var pr = new PagedResult<EntityBasic>(nodes.Length, pageNumber, pageSize)
      {
        Items = nodes.Select(_umbracoMapper.Map<EntityBasic>)
      };
      return pr;
    }
  }
}

.NET 6 libraries

V3022 Expression 'fk.DeleteRule != Rule.Cascade' is always false. xmlsaver.cs 1708


internal static bool AutoGenerated(ForeignKeyConstraint fk, bool checkRelation)
{
  ....

  if (fk.ExtendedProperties.Count > 0)
    return false;

  if (fk.AcceptRejectRule != AcceptRejectRule.None)
    return false;
  if (fk.DeleteRule != Rule.Cascade)  // <=
    return false;
  if (fk.DeleteRule != Rule.Cascade)  // <=
    return false;

  if (fk.RelatedColumnsReference.Length != 1)
    return false;
  return AutoGenerated(fk.RelatedColumnsReference[0]);
}

Squidex

V3022 Expression 'version < 7' is always false. MigrationPath.cs 55


private IEnumerable<IMigration?> ResolveMigrators(int version)
{
  yield return serviceProvider.GetRequiredService<StopEventConsumers>();

  // Version 06: Convert Event store. Must always be executed first.
  if (version < 6)
  {
    yield return serviceProvider.GetRequiredService<ConvertEventStore>();
  }

  // Version 22: Integrate Domain Id.
  if (version < 22)
  {
    yield return serviceProvider.GetRequiredService<AddAppIdToEventStream>();
  }

  // Version 07: Introduces AppId for backups.
  else if (version < 7)                                 // <=
  {
    yield return serviceProvider
                 .GetRequiredService<ConvertEventStoreAppId>();
  }

  // Version 05: Fixes the broken command architecture and requires a
  // rebuild of all snapshots.
  if (version < 5)
  {
    yield return serviceProvider.GetRequiredService<RebuildSnapshots>();
  }
  else
  {
    // Version 09: Grain indexes.
    if (version < 9)
    {
      yield return serviceProvider.GetService<ConvertOldSnapshotStores>();
    }

    ....
  }

  // Version 13: Json refactoring
  if (version < 13)
  {
    yield return serviceProvider.GetRequiredService<ConvertRuleEventsJson>();
  }

  yield return serviceProvider.GetRequiredService<StartEventConsumers>();
}

Barotrauma

V3022 Expression 'args.Length < 2' is always false. DebugConsole.cs 2183


private static void InitProjectSpecific()
{
  ....
  AssignOnClientRequestExecute(
    "setclientcharacter",
    (Client senderClient, Vector2 cursorWorldPos, string[] args) =>
    {
      if (args.Length < 2)
      {
        GameMain.Server.SendConsoleMessage("....", senderClient);
        return;
      }

      if (args.Length < 2)
      {
        ThrowError("....");
        return;
      }
    );
  ....
}

Barotrauma

V3022 Expression 'newPrice > 0' is always true. DebugConsole.cs 3310


private static void PrintItemCosts(....)
{
  if (newPrice < 1)
  {
    NewMessage(depth + materialPrefab.Name +
    " cannot be adjusted to this price, because it would become less than 1.");
    return;
  }

  ....

  if (newPrice > 0)
  {
    newPrices.TryAdd(materialPrefab, newPrice);
  }
  ....
}

Unity C# reference source code

V3022 Expression 'inputTextField.panel != null' is always true. BaseSlider.cs 648


private void UpdateTextFieldVisibility()
{
  if (showInputField)
  {
    ....
  }
  else if (inputTextField != null && inputTextField.panel != null)
  {
    if (inputTextField.panel != null)                         // <=
      inputTextField.RemoveFromHierarchy();

    inputTextField.UnregisterValueChangedCallback(OnTextFieldValueChange);
    inputTextField.UnregisterCallback<FocusOutEvent>(OnTextFieldFocusOut);
    inputTextField = null;
  }
}

Unity C# reference source code

V3022 Expression is always false. Probably the '||' operator should be used here. EditorGUIExt.cs 141


public enum EventType
{
  ....
  // Mouse button was released.
  MouseUp = 1,
  ....
  // Already processed event.
  Used = 12,
  ....
}
public static void MinMaxScroller(....)
{
  ....
  if (   Event.current.type == EventType.MouseUp
      && Event.current.type == EventType.Used)
  {
    scrollControlID = 0;
  }

  ....
}

Unity C# reference source code

V3022 Expression 'm_State.m_NewAssetIndexInList != -1' is always true. ObjectListArea.cs 511


internal void BeginNamingNewAsset(....)
{
  m_State.m_NewAssetIndexInList = m_LocalAssets.IndexOfNewText(....);
  if (m_State.m_NewAssetIndexInList != -1)
  {
    Frame(instanceID, true, false);
    GetRenameOverlay().BeginRename(newAssetName, instanceID, 0f);
  }
  else
  {
    Debug.LogError("Failed to insert new asset into list");
  }

  Repaint();
}

Unity C# reference source code

V3022 Expression '$"{material.shader.name}/"' is always not null. The operator '??' is excessive. IndexerExtensions.cs 190


internal static void MaterialShaderReferences(....)
{
  var material = context.target as Material;
  if (material == null || !material.shader)
    return;

  indexer.AddReference(context.documentIndex, "shader", material.shader);

  if (!indexer.settings.options.properties)
    return;

  var ownerPropertyType = typeof(Shader);
  var shaderName = $"{material.shader.name}/" ?? string.Empty;   // <=
  ....
}

Orleans

V3022 Expression 'value > 1 << 41 || -value > 1 << 41' is always true. Probably the '&&' operator should be used here. IntegerCodec.cs 611


public static void WriteField<TBufferWriter>
                   (ref Writer<TBufferWriter> writer,
                    uint fieldIdDelta,
                    Type expectedType,
                    long value) where TBufferWriter : IBufferWriter<byte>
{
  ReferenceCodec.MarkValueField(writer.Session);
  if (value <= int.MaxValue && value >= int.MinValue)             // <=
  {
    if (value > 1 << 20 || -value > 1 << 20)
    {
      writer.WriteFieldHeader(fieldIdDelta,
                              expectedType,
                              CodecFieldType,
                              WireType.Fixed32);
      writer.WriteInt32((int)value);
    }
    else
    {
      writer.WriteFieldHeader(fieldIdDelta,
                              expectedType,
                              CodecFieldType,
                              WireType.VarInt);
      writer.WriteVarInt64(value);
    }
  }
  else if (value > 1 << 41 || -value > 1 << 41)                   // <=
  {
    writer.WriteFieldHeader(fieldIdDelta,
                            expectedType,
                            CodecFieldType,
                            WireType.Fixed64);
    writer.WriteInt64(value);
  }
  else
  {
    writer.WriteFieldHeader(fieldIdDelta,
                            expectedType,
                            CodecFieldType,
                            WireType.VarInt);
    writer.WriteVarInt64(value);
  }
}

AvalonStudio

V3022 Expression 'IsBuiltInType(cursor.ResultType)' is always false. CPlusPlusLanguageService.cs 1105


private static StyledText InfoTextFromCursor(ClangCursor cursor)
{
  ....
  if (cursor.ResultType != null)
  {
    result.Append(cursor.ResultType.Spelling + " ",
                  IsBuiltInType(cursor.ResultType) ? theme.Keyword
                                                   : theme.Type);
  }
  else if (cursor.CursorType != null)
  {
    switch (kind)
    {
      ....
    }
    result.Append(cursor.CursorType.Spelling + " ",
                  IsBuiltInType(cursor.ResultType) ? theme.Keyword   // <=
                                                   : theme.Type);
  }
  ....
}

AvalonStudio

V3022 Expression 'mType != null && t.SupportCtorArgument == MetadataTypeCtorArgument.HintValues' is always false. CompletionEngine.cs 601


private int BuildCompletionsForMarkupExtension(....)
{
  ....
  if (t.SupportCtorArgument == MetadataTypeCtorArgument.HintValues)
  {
    ....
  }
  else if (attribName.Contains("."))
  {
    if (t.SupportCtorArgument != MetadataTypeCtorArgument.Type)
    {
      ....
      if (   mType != null
          && t.SupportCtorArgument ==
             MetadataTypeCtorArgument.HintValues)        // <=
      {
        var hints = FilterHintValues(....);
        completions.AddRange(hints.Select(.....));
      }
      ....
    }
  }
}

Discord.NET

V3022 Expression 'nextSegment == -1' is always false. CommandMapNode.cs 109


public IEnumerable<CommandMatch> GetCommands(....)
{
  ....
  int nextSegment = NextSegment(text, index, service._separatorChar);
  ....
  if (visitChildren)
  {
    ....
    if (nextSegment != -1)
    {
      name = text.Substring(index, nextSegment - index);
      if (_nodes.TryGetValue(name, out nextNode))
      {
        foreach (var cmd in
                   nextNode.GetCommands(service,
                                        nextSegment == -1 ? "" : text,  // <=
                                        nextSegment + 1,
                                        false))
          yield return cmd;
      }
    }
  }
}

.NET 7

V3022 Expression '!MetricSpec.TryParse(specString, out MetricSpec spec)' is always false. MetricsEventSource.cs 375


public static bool TryParse(string text, out MetricSpec spec)
{
  int slashIdx = text.IndexOf(MeterInstrumentSeparator);
  if (slashIdx == -1)
  {
    ....
    return true;
  }
  else
  {
    ....
    return true;
  }
}


private void ParseSpecs(string? metricsSpecs)
{
  ....
  string[] specStrings = ....
  foreach (string specString in specStrings)
  {
    if (!MetricSpec.TryParse(specString, out MetricSpec spec))   // <=
    {
      Log.Message($"Failed to parse metric spec: {specString}");
    }
    else
    {
      Log.Message($"Parsed metric: {spec}");
      ....
    }
  }
}

.NET 7

V3022 Expression 'attrib.Length == 0' is always false. Attribute.CoreCLR.cs 617


public static Attribute? GetCustomAttribute(ParameterInfo element,
                                            Type attributeType,
                                            bool inherit)
{
  // ....
  Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);

  if (attrib == null || attrib.Length == 0)
    return null;

  if (attrib.Length == 0)  // <=
    return null;

  if (attrib.Length == 1)
    return attrib[0];

  throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}

.NET 7

V3022 Expression 'writer != null' is always true. DataTable.cs 6679


protected virtual XmlSchema? GetSchema()
{
  if (GetType() == typeof(DataTable))
  {
    return null;
  }
  MemoryStream stream = new MemoryStream();

  XmlWriter writer = new XmlTextWriter(stream, null);
  if (writer != null)                                 // <=
  {
    (new XmlTreeGen(SchemaFormat.WebService)).Save(this, writer);
  }
  stream.Position = 0;
  return XmlSchema.Read(new XmlTextReader(stream), null);
}

BTCPay Server

V3022 Expression 'request.PaymentTolerance < 0 && request.PaymentTolerance > 100' is always false. Probably the '||' operator should be used here. BTCPayServer\Controllers\GreenField\GreenfieldStoresController.cs 241


private IActionResult Validate(StoreBaseData request)
{
    ....
    if (request.PaymentTolerance < 0 && request.PaymentTolerance > 100)
        ModelState.AddModelError(nameof(request.PaymentTolerance),
          "PaymentTolerance can only be between 0 and 100 percent");
    ....
}

BTCPay Server

V3022 Expression 'items == null' is always false. BTCPayServer\Services\Invoices\InvoiceRepository.cs 427


public async Task MassArchive(string[] invoiceIds, bool archive = true)
{
    using var context = _applicationDbContextFactory.CreateContext();
    var items = context.Invoices.Where(a => invoiceIds.Contains(a.Id));
    if (items == null)
    {
        return;
    }

    foreach (InvoiceData invoice in items)
    {
        invoice.Archived = archive;
    }

    await context.SaveChangesAsync();
}

public static IQueryable<TEntity> Where<TEntity>(....) where TEntity : class { return System.Linq.Queryable.Where(obj, predicate); }


RavenDB

V3022 Expression 'args.Length < 4 && args.Length > 5' is always false. Probably the '||' operator should be used here. ScriptRunner.cs 930


private JsValue Spatial_Distance(JsValue self, JsValue[] args)
{
  if (args.Length < 4 && args.Length > 5) // <=
    throw new ArgumentException("....");
}

RavenDB

V3022 Expression 'expr.Arguments.Count != 1' is always true. JavascriptCodeQueryVisitor.cs 188


public override void VisitMethod(MethodExpression expr)
{
  if (expr.Name.Value == "id" && expr.Arguments.Count == 0)
  {
    if (expr.Arguments.Count != 1)   // <=
    {
      throw new InvalidOperationException("....");
    }
    _sb.Append("this");
  }
}

MassTransit

V3022 Expression 'string.IsNullOrEmpty(binPath)' is always true. AssemblyFinder.cs 23


public static IEnumerable<Assembly> FindAssemblies(....)
{
  var assemblyPath = AppDomain.CurrentDomain.BaseDirectory;
  var binPath = string.Empty;                                           // <=

  if (string.IsNullOrEmpty(binPath))                                    // <=
    return FindAssemblies(assemblyPath,loadFailure, includeExeFiles, filter);

  if (Path.IsPathRooted(binPath))
    return FindAssemblies(binPath, loadFailure, includeExeFiles, filter);

  string[] binPaths = binPath.Split(';');
  return binPaths.SelectMany(bin =>
  {
      var path = Path.Combine(assemblyPath, bin);
      return FindAssemblies(path, loadFailure, includeExeFiles, filter);
  });
}

MassTransit

V3022 Expression 'reader.TokenType == JsonTokenType.Null' is always false. DoubleActivity_Specs.cs 55


public override Point? Read(ref Utf8JsonReader reader,
                            Type typeToConvert,
                            JsonSerializerOptions options)
{
  if (reader.TokenType != JsonTokenType.StartObject) // <=
    throw new JsonException("....");

  var originalDepth = reader.CurrentDepth;

  if (reader.TokenType == JsonTokenType.Null)        // <=
  {
    reader.Read();
    return null;
  }

  reader.Read();

  var x = double.NaN;
  var y = double.NaN;

  while (reader.TokenType == JsonTokenType.PropertyName)
  {
    ....
  }

  ....
}

Entity Framework Core

V3022 Expression 'model' is always null. The operator '?.' is meaningless. MigrationsSqlGenerator.cs 884


protected virtual IEnumerable<IReadOnlyModificationCommand>
  GenerateModificationCommands(InsertDataOperation operation,
                               IModel? model)
{
  ....

  if (   operation.ColumnTypes != null
      && operation.Columns.Length != operation.ColumnTypes.Length)
  {
    throw new InvalidOperationException(
        RelationalStrings.InsertDataOperationTypesCountMismatch(
            ....,
            FormatTable(operation.Table,
                        operation.Schema ?? model?.GetDefaultSchema())));
  }

  if (operation.ColumnTypes == null && model == null)
  {
    throw new InvalidOperationException(
        RelationalStrings.InsertDataOperationNoModel(
            FormatTable(operation.Table,
                        operation.Schema ?? model?.GetDefaultSchema())));
  }
  ....
}

Microsoft PowerToys

V3022 Expression 'ind' is always not null. The operator '??' is excessive. StringMatcher.cs 230


private static int CalculateClosestSpaceIndex(List<int> spaceIndices,
                                              int firstMatchIndex)
{
  if (spaceIndices.Count == 0)
  {
    return -1;
  }
  else
  {
    int? ind = spaceIndices.OrderBy(item => (firstMatchIndex - item))
                           .Where(item => firstMatchIndex > item)
                           .FirstOrDefault();
    int closestSpaceIndex = ind ?? -1;          // <=
    return closestSpaceIndex;
  }
}

Power-Fx

V3022 [CWE-570] Expression 'i > Args.Count && i < 0' is always false. CallNode.cs 53


public bool TryGetArgument(int i, out IntermediateNode arg)
{
    arg = default;
    if (i > Args.Count && i < 0)
    {
        return false;
    }

    arg = Args[i];
    return true;
}

Power-Fx

V3022 [CWE-570] Expression 'i > Args.Count && i < 0' is always false. CallNode.cs 64


public bool IsLambdaArg(int i)
{
    if (i > Args.Count && i < 0)
    {
        return false;
    }

    return Args[i] is LazyEvalNode;
}

.NET 8

V3022 Expression '_validationState == ValidatingReaderState.OnReadBinaryContent' is always false. XsdValidatingReader.cs 1302


public override void MoveToAttribute(int i)
{
  ....
  _currentAttrIndex = i;
  if (i < _coreReaderAttributeCount)
  {
    ....
    _validationState = ValidatingReaderState.OnAttribute;
  }
  else
  {
    ....
    _validationState = ValidatingReaderState.OnDefaultAttribute;
  }

  if (_validationState == ValidatingReaderState.OnReadBinaryContent)
  {
    Debug.Assert(_readBinaryHelper != null);
    _readBinaryHelper.Finish();
    _validationState = _savedState;
  }
}

nopCommerce

V3022 Expression 'string.IsNullOrEmpty(conditionAttributeXml)' is always false. AttributeParser.cs 499


public async Task<bool?> IsConditionMetAsync(string conditionAttributeXml,
                                             string selectedAttributesXml)
{
  if (string.IsNullOrEmpty(conditionAttributeXml))
    return null;

  if (string.IsNullOrEmpty(conditionAttributeXml))
    //no condition
    return null;

  ....
}