To get a trial key
fill out the form below
Team License (a basic version)
Enterprise License (extended version)
* By clicking this button you agree to our Privacy Policy statement

Request our prices
New License
License Renewal
--Select currency--
USD
EUR
GBP
RUB
* By clicking this button you agree to our Privacy Policy statement

Free PVS-Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

>
>
>
Examples of errors detected by the V302…

Examples of errors detected by the V3022 diagnostic

V3022. Expression is always true/false.


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;
    }
  }
  ....
}

.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.

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;
}

This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →
Accept