V3022. Expression is always true/false.
V3022 Expression 'memberValue == null && (memberType == Globals.TypeOfObject || (originValueIsNullableOfT && memberType.IsValueType))' is always false. ReflectionClassWriter.cs 94
public static void ReflectionWriteValue(....)
{
....
if (memberValue == null) // <=
{
context.WriteNull(xmlWriter,
memberType,
DataContract.IsTypeSerializable(memberType));
}
else
{
PrimitiveDataContract? primitiveContract = ....;
if ( primitiveContract != null
&& primitiveContract.UnderlyingType != Globals.TypeOfObject
&& !writeXsiType)
{
primitiveContract.WriteXmlValue(xmlWriter, memberValue, context);
}
else
{
if ( memberValue == null // <=
&& ( memberType == Globals.TypeOfObject
|| (originValueIsNullableOfT && memberType.IsValueType)))
{
context.WriteNull(xmlWriter,
memberType,
DataContract.IsTypeSerializable(memberType));
}
else
{
ReflectionInternalSerialize(xmlWriter,
context,
memberValue!,
memberValue!.GetType()
.TypeHandle
.Equals(memberType.TypeHandle),
writeXsiType,
memberType,
originValueIsNullableOfT);
}
}
}
....
}
V3022 Expression 'lastResponseMessage' is always null. The operator '?.' is meaningless. SemanticKernelAIAgent.cs 111
public override async Task<MAAI.AgentRunResponse>
RunAsync(IEnumerable<ChatMessage> messages,
MAAI.AgentThread? thread = null,
MAAI.AgentRunOptions? options = null,
CancellationToken cancellationToken = default)
{
....
AgentResponseItem<ChatMessageContent>? lastResponseItem = null;
ChatMessage? lastResponseMessage = null; // <=
await foreach (var responseItem in ....)
{
lastResponseItem = responseItem;
}
return new MAAI.AgentRunResponse(responseMessages)
{
AgentId = this._innerAgent.Id,
RawRepresentation = lastResponseItem,
AdditionalProperties = lastResponseMessage?.AdditionalProperties, // <=
CreatedAt = lastResponseMessage?.CreatedAt, // <=
};
}
Similar errors can be found in some other places:
V3022 Expression 'totalBounds' is always null. The operator '?.' is meaningless. MergeNode.cs 87
public override RectD? GetPreviewBounds(int frame,
string elementToRenderName = "")
{
....
RectD? totalBounds = null;
if ( Top.Connection != null
&& Top.Connection.Node is IPreviewRenderable topPreview)
{
var topBounds = topPreview.GetPreviewBounds(frame, elementToRenderName);
if (topBounds != null)
{
totalBounds = totalBounds?.Union(topBounds.Value) ?? topBounds;
}
}
....
}
V3022 Expression is always true. Probably the '&&' operator should be used here. Files.App App.xaml.cs 181
private void Window_Activated(object sender, WindowActivatedEventArgs args)
{
AppModel.IsMainWindowClosed = false;
// TODO(s): Is this code still needed?
if (args.WindowActivationState != WindowActivationState.CodeActivated ||
args.WindowActivationState != WindowActivationState.PointerActivated)
return;
ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] =
-Environment.ProcessId;
}
V3022 [CWE-571] Expression is always true. Probably the '&&' operator should be used here. OVRCubemapCapture.cs 201
public static bool SaveCubemapCapture(....)
{
....
dirName = Path.GetDirectoryName(pathName);
fileName = Path.GetFileName(pathName);
if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
dirName += "/";
....
}
V3022 Expression 'FrugalListStoreState.Success == Add(oldList.EntryAt(index))' is always true. FrugalList.cs 1473
public override void Promote(FrugalListBase<T> oldList)
{
for (var index = 0; index < oldList.Count; ++index)
{
if (FrugalListStoreState.Success == Add(oldList.EntryAt(index)))
{
continue;
}
....
}
}
public override FrugalListStoreState Add(T value)
{
....
return FrugalListStoreState.Success;
}
V3022 Expression 'Type == TokenType.UnknownSymbol' is always false. SqliteSyntaxReader.cs 166
public TokenType Read()
{
....
if (Type == TokenType.UnknownSymbol) // <=
{
Value = Buffer[Index].ToString();
Index++;
return Type;
}
....
if ( end >= Buffer.Length
|| Buffer[end] == ','
|| Buffer[end] == ')'
|| Buffer[end] == '('
|| char.IsWhiteSpace(Buffer[end]))
{
Index = end;
}
else if (Type == TokenType.UnknownSymbol) // <=
{
Value = Buffer[Index].ToString();
Index++;
return Type;
}
....
}
V3022 Expression 'mediaInfo.VideoHdrFormatCompatibility.ContainsIgnoreCase("dolby")' is always false. 199_mediainfo_to_ffmpeg.cs 351
private HdrFormat MigrateHdrFormat(MediaInfo198 mediaInfo)
{
if (mediaInfo.VideoHdrFormatCompatibility
.IsNotNullOrWhiteSpace())
{
if (mediaInfo.VideoHdrFormatCompatibility
.ContainsIgnoreCase("HLG"))
{
return HdrFormat.Hlg10;
}
if (mediaInfo.VideoHdrFormatCompatibility
.ContainsIgnoreCase("dolby"))
{
return HdrFormat.DolbyVision;
}
if (mediaInfo.VideoHdrFormatCompatibility
.ContainsIgnoreCase("dolby")) // <=
{
return HdrFormat.DolbyVision; // <=
}
if (mediaInfo.VideoHdrFormatCompatibility
.ContainsIgnoreCase("hdr10+"))
{
return HdrFormat.Hdr10Plus;
}
if (mediaInfo.VideoHdrFormatCompatibility
.ContainsIgnoreCase("hdr10"))
{
return HdrFormat.Hdr10;
}
....
}
....
}
V3022 Expression '3 != _docState || 9 != _docState' is always true. Probably the '&&' operator should be used here. XmlBinaryReader.cs 3026
private void ImplReadElement()
{
if (3 != _docState || 9 != _docState)
{
switch (_docState)
{
....
}
}
}
V3022 Expression 'EncodeVideo(mediaSource)' is always false. EncodedRecorder.cs 128
private string GetCommandLineArgs(MediaSourceInfo mediaSource,
string inputTempFile, string targetFile)
{
....
if (EncodeVideo(mediaSource)) // <=
{
const int MaxBitrate = 25000000;
videoArgs = string.Format(CultureInfo.InvariantCulture,
"-codec:v:0 libx264 -force_key_frames \
"expr:gte(t,n_forced*5)\" {0}
-pix_fmt yuv420p -preset superfast -crf 23
-b:v {1} -maxrate {1} -bufsize ({1}*2) -profile:v high
-level 41",GetOutputSizeParam(),MaxBitrate);
}
....
}
private static bool EncodeVideo(MediaSourceInfo mediaSource)
{
return false;
}
V3022 Expression 'condition.Condition == ProfileConditionType.GreaterThanEqual' is always false. StreamBuilder.cs 2193
private void ApplyTranscodingConditions(....)
{
....
if (condition.Condition ==
ProfileConditionType.GreaterThanEqual) // <=
{
continue;
}
switch (condition.Property)
{
case ProfileConditionValue.AudioBitrate:
{
....
else if (condition.Condition ==
ProfileConditionType.GreaterThanEqual) // <=
{
....
}
break;
}
case ProfileConditionValue.AudioSampleRate:
{
....
else if (condition.Condition ==
ProfileConditionType.GreaterThanEqual) // <=
{
....
}
break;
....
}
}
}
V3022 Expression 'Text.Length == 10' is always false. TimeBox.cs 338
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
....
if ( (e.Key == Key.OemQuestion || e.Key == Key.OemPeriod)
&& (Keyboard.Modifiers & ModifierKeys.Control) == 0)
{
if (Text.Length > 8) // <=
{
e.Handled = true;
return;
}
if (Text.Length == 1){....}
else if (Text.Length == 4) {....}
else if (Text.Length == 7) {....}
else if (Text.Length == 10) // <=
Text = Text.Substring(0, 9) + Text.Substring(6, 1).PadLeft(3, '0');
SelectionStart = Text.Length;
e.Handled = true;
return;
}
....
}
V3022 Expression 'ch < '0' && ch > '9'' is always false. Probably the '||' operator should be used here. TMP_PhoneNumberValidator.cs 20
public override char Validate(ref string text, ref int pos, char ch)
{
Debug.Log("Trying to validate...");
// Return unless the character is a valid digit
if (ch < '0' && ch > '9') return (char)0;
....
}
V3022 Expression 'options.meshExportType != null && string.IsNullOrEmpty(options.meshExportMaterialRepo) && options.outpath is null' is always false. UncookTask.cs 44
public int UncookTask(FileSystemInfo[] paths, UncookTaskOptions options)
{
....
if (options.outpath == null) // <=
{
_loggerService.Error("Please fill in an output path.");
return ERROR_BAD_ARGUMENTS;
}
if ( options.meshExportType != null
&& string.IsNullOrEmpty(options.meshExportMaterialRepo)
&& options.outpath is null) // <=
{
_loggerService.Error("When using --mesh-export-type, the --outpath" +
" or the --mesh-export-material-repo must be specified.");
return ERROR_INVALID_COMMAND_LINE;
}
}
V3022 Expression 'slotMap[slot].workerId < 0' is always false. Unsigned type value is always >= 0. ClusterConfig.cs 460
public struct HashSlot
{
....
public ushort workerId => ....;
}
public long GetConfigEpochFromSlot(int slot)
{
if (slotMap[slot].workerId < 0)
return 0;
return workers[slotMap[slot].workerId].configEpoch;
}
V3022 Expression 'status == OperationStatus.SUCCESS' is always false. LockableContext.cs 133
internal static void DoInternalLock<....>(....)
{
OperationStatus status;
if (cancellationToken.IsCancellationRequested)
status = OperationStatus.CANCELED;
else
{
status = DoInternalLock(clientSession, key);
if (status == OperationStatus.SUCCESS)
continue; // Success; continue to the next key.
}
var unlockIdx = keyIdx - (status == OperationStatus.SUCCESS ? 0 : 1);
}
V3022 Expression 'isGolem' is always false. Minion.cs 230
public override bool Reveal(....)
{
bool isGolem = false;
if (this is BaseGolem ||
this is IceGolem ||
this is BoneGolem ||
this is DecayGolem ||
this is ConsumeFleshGolem ||
this is BloodGolem)
{
....
isGolem = false;
}
....
if (....)
player.InGameClient.SendMessage(new PetMessage()
{
....
Index = isGolem ? 9 : player.CountFollowers(SNO) + PlusIndex,
....
});
}
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;
....
}
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;
}
}
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;
}
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;
}
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;
}
}
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())));
}
....
}
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)
{
....
}
....
}
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);
});
}
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");
}
}
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("....");
}
V3022 Expression 'items == null' is always false. 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); }
V3022 Expression 'request.PaymentTolerance < 0 && request.PaymentTolerance > 100' is always false. Probably the '||' operator should be used here. 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");
....
}
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);
}
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);
}
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}");
....
}
}
}
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;
}
}
}
}
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(.....));
}
....
}
}
}
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);
}
....
}
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);
}
}
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; // <=
....
}
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();
}
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;
}
....
}
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;
}
}
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);
}
....
}
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;
}
);
....
}
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>();
}
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]);
}
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;
}
}
}
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);
}
....
}
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));
}
....
}
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)
....
}
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)
....
}
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);
}
....
}
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;
....
}
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;
}
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 '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);
}
}
}
....
}
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;
}
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);
}
}
....
}
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);
}
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();
}
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;
}
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 '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 '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
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;
}
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();
}
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
}
}
....
}
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;
}
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); // <=
}
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();
}
}
}
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);
}
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();
....
}
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 '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");
....
}
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("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;
}
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 '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;
}
}
}
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;
}
....
}
....
}
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();
}
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(....);
}
....
}
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;
}
....
}
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;
}
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) // <=
{
....
}
....
}
....
}
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;
}
....
}
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(....);
}
}
....
}
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);
....
}
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;
}
....
}
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)
{
....
}
}
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);
}
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(....);
....
}
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."
);
}
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;
}
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(....);
}
....
}
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);
}
....
}
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));
}
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 [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);
}
....
}
....
}
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 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 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;
}
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();
....
}
....
}
....
}
}
}
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 '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 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 'automationJob != null && automationJob == null' is always false. NodeConfigurationDeployment.cs 199
public NodeConfigurationDeployment(
....,
Management.Automation.Models.Job automationJob = null,
....)
{
....
if (automationJob != null && automationJob == null) return;
....
}
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");
}
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; // <=
....
}
....
}
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;
}
....
}
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);
}
}
}
....
}
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;
}
....
}
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)
....
....
}
V3022 Expression '!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " "' is always true. OdbcCommandBuilder.cs 338
public string UnquoteIdentifier(....)
{
....
if (!string.IsNullOrEmpty(quotePrefix) || quotePrefix != " ")
....
....
}
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 '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)
{ .... }
....
}
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;
}
}
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) // <=
{
....
}
....
}
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 { .... }
....
}
....
}
....
}
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());
}
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");
....
}
....
}
....
}
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;
}
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;
}
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-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;
}
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-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;
}
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 $"....";
}
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);
}
....
}
....
}
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);
....
}
....
}
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 '"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 '!stop' is always true. template.cs 229
public Control parseStringBuilder(....)
{
....
bool stop = false;
....
while (!stop)
{
....
}
....
}
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 '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 '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;
}
....
}
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 '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 '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 '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 '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
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)
....
}
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";
}
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);
}
}
....
}
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;
....
}
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 '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 '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 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();
}
}
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;
}
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;
}
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();
....
}
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;
}
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;
}
}
....
}
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,
....);
}
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(....);
}
....
}
....
}
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, // <=
....
};
....
}
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;
}
....
}
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 && ....) // <=
{
....
}
}
V3022 Expression '_dragOverMode == DragItemPositioning.None' is always false. TreeNode.cs 566
private void UpdateDragPositioning(....)
{
if (....)
_dragOverMode = DragItemPositioning.Above;
else if (....)
_dragOverMode = DragItemPositioning.Below;
else
_dragOverMode = DragItemPositioning.At;
// Update DraggedOverNode
var tree = ParentTree;
if (_dragOverMode == DragItemPositioning.None) // <=
{
if (tree != null && tree.DraggedOverNode == this)
tree.DraggedOverNode = null;
}
else if (tree != null)
tree.DraggedOverNode = this;
}