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.


Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show again