From c7bc25aa17e142e2acdcd7edd895fbdc5c3f3115 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 24 Mar 2026 00:42:59 +0000 Subject: [PATCH] refactor: convert == null / != null to is null / is not null in 31 files Replace old-style null comparisons with modern C# pattern matching syntax across Commands, Protocol, Mapping, ChatBots, Physics, Inventory, Logger, CommandHandler, Scripting, Crypto, and other modules. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- MinecraftClient/ChatBots/AutoCraft.cs | 4 ++-- MinecraftClient/ChatBots/Map.cs | 4 ++-- MinecraftClient/ChatBots/Script.cs | 6 +++--- MinecraftClient/ChatBots/TelegramBridge.cs | 4 ++-- .../ArgumentType/LocationArgumentType.cs | 6 +++--- MinecraftClient/CommandHandler/CmdResult.cs | 2 +- MinecraftClient/Commands/Bots.cs | 2 +- MinecraftClient/Commands/Chunk.cs | 16 ++++++++-------- MinecraftClient/Commands/Enchant.cs | 4 ++-- MinecraftClient/Commands/Inventory.cs | 10 +++++----- MinecraftClient/Crypto/AesCfb8Stream.cs | 8 ++++---- MinecraftClient/FileMonitor.cs | 4 ++-- MinecraftClient/Inventory/Container.cs | 2 +- .../Inventory/EnchantmentMapping.cs | 6 +++--- MinecraftClient/Logger/FilteredLogger.cs | 2 +- .../BlockPalettes/BlockPaletteGenerator.cs | 2 +- MinecraftClient/Mapping/Dimension.cs | 2 +- .../Mapping/EntityPalettes/EntityPalette.cs | 4 ++-- MinecraftClient/Mapping/Location.cs | 4 ++-- MinecraftClient/Physics/BlockShapes.cs | 8 ++++---- .../Protocol/Handlers/Protocol16.cs | 6 +++--- .../Protocol/Handlers/Protocol18Forge.cs | 2 +- .../Protocol/Handlers/SocketWrapper.cs | 2 +- .../Protocol/Message/ChatMessage.cs | 2 +- .../Protocol/Message/LastSeenMessageList.cs | 6 +++--- .../Protocol/ProfileKey/KeyUtils.cs | 18 +++++++++--------- .../Protocol/ProfileKey/PlayerKeyPair.cs | 4 ++-- .../Protocol/ProfileKey/PublicKey.cs | 4 ++-- .../Protocol/Session/SessionToken.cs | 4 ++-- .../Scripting/DynamicRun/Builder/Compiler.cs | 2 +- MinecraftClient/Settings.cs | 4 ++-- 31 files changed, 77 insertions(+), 77 deletions(-) diff --git a/MinecraftClient/ChatBots/AutoCraft.cs b/MinecraftClient/ChatBots/AutoCraft.cs index 151826f5..bc8bf957 100644 --- a/MinecraftClient/ChatBots/AutoCraft.cs +++ b/MinecraftClient/ChatBots/AutoCraft.cs @@ -276,7 +276,7 @@ namespace MinecraftClient.ChatBots /// so that it can be used in crafting table public static Recipe ConvertToCraftingTable(Recipe recipe) { - if (recipe.CraftingAreaType == ContainerType.PlayerInventory && recipe.Materials != null) + if (recipe.CraftingAreaType == ContainerType.PlayerInventory && recipe.Materials is not null) { if (recipe.Materials.ContainsKey(4)) { @@ -500,7 +500,7 @@ namespace MinecraftClient.ChatBots } } - if (recipe.Materials != null) + if (recipe.Materials is not null) { foreach (KeyValuePair slot in recipe.Materials) { diff --git a/MinecraftClient/ChatBots/Map.cs b/MinecraftClient/ChatBots/Map.cs index 6a9f6bc4..930e057e 100644 --- a/MinecraftClient/ChatBots/Map.cs +++ b/MinecraftClient/ChatBots/Map.cs @@ -284,13 +284,13 @@ namespace MinecraftClient.ChatBots if (Config.Send_Rendered_To_Discord) { - if (discordBridge == null || (discordBridge != null && !discordBridge.IsConnected)) + if (discordBridge is null || (discordBridge is not null && !discordBridge.IsConnected)) return; } if (Config.Send_Rendered_To_Telegram) { - if (telegramBridge == null || (telegramBridge != null && !telegramBridge.IsConnected)) + if (telegramBridge is null || (telegramBridge is not null && !telegramBridge.IsConnected)) return; } diff --git a/MinecraftClient/ChatBots/Script.cs b/MinecraftClient/ChatBots/Script.cs index 16ca9311..b4da57b4 100644 --- a/MinecraftClient/ChatBots/Script.cs +++ b/MinecraftClient/ChatBots/Script.cs @@ -154,7 +154,7 @@ namespace MinecraftClient.ChatBots if (csharp) //C# compiled script { //Initialize thread on first update - if (thread == null) + if (thread is null) { thread = new Thread(() => { @@ -166,7 +166,7 @@ namespace MinecraftClient.ChatBots { string errorMessage = string.Format(Translations.bot_script_fail, file, e.ExceptionType); LogToConsole(errorMessage); - if (owner != null) + if (owner is not null) SendPrivateMessage(owner, errorMessage); LogToConsole(e.InnerException); } @@ -178,7 +178,7 @@ namespace MinecraftClient.ChatBots } //Unload bot once the thread has finished running - if (thread != null && !thread.IsAlive) + if (thread is not null && !thread.IsAlive) { UnloadBot(); } diff --git a/MinecraftClient/ChatBots/TelegramBridge.cs b/MinecraftClient/ChatBots/TelegramBridge.cs index 1140756a..70536cb9 100644 --- a/MinecraftClient/ChatBots/TelegramBridge.cs +++ b/MinecraftClient/ChatBots/TelegramBridge.cs @@ -148,7 +148,7 @@ namespace MinecraftClient.ChatBots private void Disconnect() { - if (botClient != null) + if (botClient is not null) { try { @@ -238,7 +238,7 @@ namespace MinecraftClient.ChatBots private bool CanSendMessages() { - return botClient != null && !string.IsNullOrEmpty(Config.ChannelId.Trim()) && bridgeDirection != BridgeDirection.Minecraft; + return botClient is not null && !string.IsNullOrEmpty(Config.ChannelId.Trim()) && bridgeDirection != BridgeDirection.Minecraft; } async Task MainAsync() diff --git a/MinecraftClient/CommandHandler/ArgumentType/LocationArgumentType.cs b/MinecraftClient/CommandHandler/ArgumentType/LocationArgumentType.cs index f2ef9b0a..fbd8a4dc 100644 --- a/MinecraftClient/CommandHandler/ArgumentType/LocationArgumentType.cs +++ b/MinecraftClient/CommandHandler/ArgumentType/LocationArgumentType.cs @@ -51,7 +51,7 @@ namespace MinecraftClient.CommandHandler.ArgumentType string[] args = builder.Remaining.Split(' ', StringSplitOptions.TrimEntries); if (args.Length == 0 || (args.Length == 1 && string.IsNullOrWhiteSpace(args[0]))) { - if (client != null) + if (client is not null) { Location current = client.GetCurrentLocation(); builder.Suggest(string.Format("{0:0.00}", current.X)); @@ -68,7 +68,7 @@ namespace MinecraftClient.CommandHandler.ArgumentType else if (args.Length == 1 || (args.Length == 2 && string.IsNullOrWhiteSpace(args[1]))) { string add = args.Length == 1 ? " " : string.Empty; - if (client != null) + if (client is not null) { Location current = client.GetCurrentLocation(); builder.Suggest(string.Format("{0}{2}{1:0.00}", builder.Remaining, current.Y, add)); @@ -83,7 +83,7 @@ namespace MinecraftClient.CommandHandler.ArgumentType else if (args.Length == 2 || (args.Length == 3 && string.IsNullOrWhiteSpace(args[2]))) { string add = args.Length == 2 ? " " : string.Empty; - if (client != null) + if (client is not null) { Location current = client.GetCurrentLocation(); builder.Suggest(string.Format("{0}{2}{1:0.00}", builder.Remaining, current.Z, add)); diff --git a/MinecraftClient/CommandHandler/CmdResult.cs b/MinecraftClient/CommandHandler/CmdResult.cs index 8ecafc8a..9c4cd840 100644 --- a/MinecraftClient/CommandHandler/CmdResult.cs +++ b/MinecraftClient/CommandHandler/CmdResult.cs @@ -87,7 +87,7 @@ namespace MinecraftClient.CommandHandler public override string ToString() { - if (result != null) + if (result is not null) return result; else return status.ToString(); diff --git a/MinecraftClient/Commands/Bots.cs b/MinecraftClient/Commands/Bots.cs index 73574a14..9a94615e 100644 --- a/MinecraftClient/Commands/Bots.cs +++ b/MinecraftClient/Commands/Bots.cs @@ -84,7 +84,7 @@ namespace MinecraftClient.Commands else { ChatBot? bot = handler.GetLoadedChatBots().Find(bot => bot.GetType().Name.ToLower() == botName.ToLower()); - if (bot == null) + if (bot is null) return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_bots_notfound, botName)); else { diff --git a/MinecraftClient/Commands/Chunk.cs b/MinecraftClient/Commands/Chunk.cs index 2068c662..cbf82173 100644 --- a/MinecraftClient/Commands/Chunk.cs +++ b/MinecraftClient/Commands/Chunk.cs @@ -92,7 +92,7 @@ namespace MinecraftClient.Commands sb.Append('\n'); sb.AppendLine(string.Format(Translations.cmd_chunk_current, current, current.ChunkX, current.ChunkZ)); - if (markedChunkPos != null) + if (markedChunkPos is not null) { sb.Append(Translations.cmd_chunk_marked); if (pos.HasValue) @@ -120,7 +120,7 @@ namespace MinecraftClient.Commands { for (int x = startX; x <= endX; ++x) { - if (world[x, z] != null) + if (world[x, z] is not null) { leftMost = Math.Min(leftMost, x); rightMost = Math.Max(rightMost, x); @@ -184,7 +184,7 @@ namespace MinecraftClient.Commands } // Try to include the marker chunk - if (markedChunkPos != null && + if (markedChunkPos is not null && (((Math.Max(bottomMost, markChunkZ) - Math.Min(topMost, markChunkZ) + 1) > consoleHeight) || ((Math.Max(rightMost, markChunkX) - Math.Min(leftMost, markChunkX) + 1) > consoleWidth))) sb.AppendLine(Translations.cmd_chunk_outside); @@ -212,7 +212,7 @@ namespace MinecraftClient.Commands sb.Append("§§4"); // Marked chunk: background red ChunkColumn? chunkColumn = world[x, z]; - if (chunkColumn == null) + if (chunkColumn is null) sb.Append(chunkStatusStr[0]); else if (chunkColumn.FullyLoaded) sb.Append(chunkStatusStr[2]); @@ -242,10 +242,10 @@ namespace MinecraftClient.Commands handler.Log.Info(Translations.cmd_chunk_for_debug); (int chunkX, int chunkZ) = markedChunkPos ?? new(pos!.Value.ChunkX, pos!.Value.ChunkZ); ChunkColumn? chunkColumn = handler.GetWorld()[chunkX, chunkZ]; - if (chunkColumn != null) + if (chunkColumn is not null) chunkColumn.FullyLoaded = false; - if (chunkColumn == null) + if (chunkColumn is null) return r.SetAndReturn(Status.Fail, "Fail: chunk dosen't exist!"); else return r.SetAndReturn(Status.Done, string.Format("Successfully marked chunk ({0}, {1}) as loading.", chunkX, chunkZ)); @@ -262,10 +262,10 @@ namespace MinecraftClient.Commands handler.Log.Info(Translations.cmd_chunk_for_debug); (int chunkX, int chunkZ) = markedChunkPos ?? new(pos!.Value.ChunkX, pos!.Value.ChunkZ); ChunkColumn? chunkColumn = handler.GetWorld()[chunkX, chunkZ]; - if (chunkColumn != null) + if (chunkColumn is not null) chunkColumn.FullyLoaded = false; - if (chunkColumn == null) + if (chunkColumn is null) return r.SetAndReturn(Status.Fail, "Fail: chunk dosen't exist!"); else return r.SetAndReturn(Status.Done, string.Format("Successfully marked chunk ({0}, {1}) as loaded.", chunkX, chunkZ)); diff --git a/MinecraftClient/Commands/Enchant.cs b/MinecraftClient/Commands/Enchant.cs index 813c734f..1fc361f7 100644 --- a/MinecraftClient/Commands/Enchant.cs +++ b/MinecraftClient/Commands/Enchant.cs @@ -66,7 +66,7 @@ namespace MinecraftClient.Commands } } - if (enchantingTable == null) + if (enchantingTable is null) return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_enchanting_table_not_opened); int[] emptySlots = enchantingTable.GetEmpytSlots(); @@ -84,7 +84,7 @@ namespace MinecraftClient.Commands EnchantmentData? enchantment = handler.GetLastEnchantments(); - if (enchantment == null) + if (enchantment is null) return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_enchant_no_enchantments); short requiredLevel = slotId switch diff --git a/MinecraftClient/Commands/Inventory.cs b/MinecraftClient/Commands/Inventory.cs index c0397b08..cc0aeac4 100644 --- a/MinecraftClient/Commands/Inventory.cs +++ b/MinecraftClient/Commands/Inventory.cs @@ -276,7 +276,7 @@ namespace MinecraftClient.Commands } Container? inventory = handler.GetInventory(inventoryId.Value); - if (inventory == null) + if (inventory is null) return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId)); if (handler.CloseInventory(inventoryId.Value)) @@ -299,7 +299,7 @@ namespace MinecraftClient.Commands } Container? inventory = handler.GetInventory(inventoryId.Value); - if (inventory == null) + if (inventory is null) return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId)); StringBuilder response = new(); @@ -307,7 +307,7 @@ namespace MinecraftClient.Commands response.AppendLine(String.Format(" #{0} - {1}§8", inventoryId, inventory.Title)); string? asciiArt = inventory.Type.GetAsciiArt(); - if (asciiArt != null && Settings.Config.Main.Advanced.ShowInventoryLayout) + if (asciiArt is not null && Settings.Config.Main.Advanced.ShowInventoryLayout) response.AppendLine(asciiArt); int selectedHotbar = handler.GetCurrentSlot() + 1; @@ -342,7 +342,7 @@ namespace MinecraftClient.Commands } Container? inventory = handler.GetInventory(inventoryId.Value); - if (inventory == null) + if (inventory is null) return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId)); string keyName = actionType switch @@ -373,7 +373,7 @@ namespace MinecraftClient.Commands } Container? inventory = handler.GetInventory(inventoryId.Value); - if (inventory == null) + if (inventory is null) return r.SetAndReturn(CmdResult.Status.Fail, string.Format(Translations.cmd_inventory_not_exist, inventoryId)); // check item exist diff --git a/MinecraftClient/Crypto/AesCfb8Stream.cs b/MinecraftClient/Crypto/AesCfb8Stream.cs index dfa2dd78..b60eb845 100644 --- a/MinecraftClient/Crypto/AesCfb8Stream.cs +++ b/MinecraftClient/Crypto/AesCfb8Stream.cs @@ -89,7 +89,7 @@ namespace MinecraftClient.Crypto } Span blockOutput = stackalloc byte[blockSize]; - if (FastAes != null) + if (FastAes is not null) FastAes.EncryptEcb(ReadStreamIV, blockOutput); else Aes!.EncryptEcb(ReadStreamIV, blockOutput, PaddingMode.None); @@ -122,7 +122,7 @@ namespace MinecraftClient.Crypto } int processEnd = readed + curRead; - if (FastAes != null) + if (FastAes is not null) { for (int idx = readed; idx < processEnd; idx++) { @@ -161,7 +161,7 @@ namespace MinecraftClient.Crypto { Span blockOutput = stackalloc byte[blockSize]; - if (FastAes != null) + if (FastAes is not null) FastAes.EncryptEcb(WriteStreamIV, blockOutput); else Aes!.EncryptEcb(WriteStreamIV, blockOutput, PaddingMode.None); @@ -185,7 +185,7 @@ namespace MinecraftClient.Crypto for (int wirtten = 0; wirtten < required; ++wirtten) { ReadOnlySpan blockInput = new(outputBuf, wirtten, blockSize); - if (FastAes != null) + if (FastAes is not null) FastAes.EncryptEcb(blockInput, blockOutput); else Aes!.EncryptEcb(blockInput, blockOutput, PaddingMode.None); diff --git a/MinecraftClient/FileMonitor.cs b/MinecraftClient/FileMonitor.cs index 36e89ec1..16f590a4 100644 --- a/MinecraftClient/FileMonitor.cs +++ b/MinecraftClient/FileMonitor.cs @@ -59,9 +59,9 @@ namespace MinecraftClient /// public void Dispose() { - if (monitor != null) + if (monitor is not null) monitor.Item1.Dispose(); - if (polling != null) + if (polling is not null) polling.Item2.Cancel(); } diff --git a/MinecraftClient/Inventory/Container.cs b/MinecraftClient/Inventory/Container.cs index a5ecd92d..98908655 100644 --- a/MinecraftClient/Inventory/Container.cs +++ b/MinecraftClient/Inventory/Container.cs @@ -172,7 +172,7 @@ namespace MinecraftClient.Inventory public int[] SearchItem(ItemType itemType) { List result = new(); - if (Items != null) + if (Items is not null) { foreach (var item in Items) { diff --git a/MinecraftClient/Inventory/EnchantmentMapping.cs b/MinecraftClient/Inventory/EnchantmentMapping.cs index 2c66b40f..6bab6117 100644 --- a/MinecraftClient/Inventory/EnchantmentMapping.cs +++ b/MinecraftClient/Inventory/EnchantmentMapping.cs @@ -273,7 +273,7 @@ namespace MinecraftClient.Inventory public static Enchantments GetEnchantmentByRegistryId1206(int id) { - if (dynamicEnchantmentIdMap != null && dynamicEnchantmentIdMap.TryGetValue(id, out var dynValue)) + if (dynamicEnchantmentIdMap is not null && dynamicEnchantmentIdMap.TryGetValue(id, out var dynValue)) return dynValue; if (enchantmentMappings.TryGetValue((short)id, out var value)) return value; @@ -282,10 +282,10 @@ namespace MinecraftClient.Inventory public static int GetRegistryId1206ByEnchantment(Enchantments enchantment) { - if (reverseEnchantmentMappings == null) + if (reverseEnchantmentMappings is null) { reverseEnchantmentMappings = new(); - if (dynamicEnchantmentIdMap != null) + if (dynamicEnchantmentIdMap is not null) { foreach (var kvp in dynamicEnchantmentIdMap) reverseEnchantmentMappings[kvp.Value] = (short)kvp.Key; diff --git a/MinecraftClient/Logger/FilteredLogger.cs b/MinecraftClient/Logger/FilteredLogger.cs index 168e126b..09a3596c 100644 --- a/MinecraftClient/Logger/FilteredLogger.cs +++ b/MinecraftClient/Logger/FilteredLogger.cs @@ -31,7 +31,7 @@ namespace MinecraftClient.Logger regexToUse = new(debug); break; } - if (regexToUse != null) + if (regexToUse is not null) { // IsMatch and white/blacklist result can be represented using XOR // e.g. matched(true) ^ blacklist(true) => shouldn't log(false) diff --git a/MinecraftClient/Mapping/BlockPalettes/BlockPaletteGenerator.cs b/MinecraftClient/Mapping/BlockPalettes/BlockPaletteGenerator.cs index 1c835892..11f7f5d2 100644 --- a/MinecraftClient/Mapping/BlockPalettes/BlockPaletteGenerator.cs +++ b/MinecraftClient/Mapping/BlockPalettes/BlockPaletteGenerator.cs @@ -137,7 +137,7 @@ namespace MinecraftClient.Mapping.BlockPalettes File.WriteAllLines(outputPalettePath, outFile); - if (outputEnum != null) + if (outputEnum is not null) { outFile = new List(); outFile.AddRange(new[] { diff --git a/MinecraftClient/Mapping/Dimension.cs b/MinecraftClient/Mapping/Dimension.cs index fe52b0e0..f9e8380f 100644 --- a/MinecraftClient/Mapping/Dimension.cs +++ b/MinecraftClient/Mapping/Dimension.cs @@ -129,7 +129,7 @@ namespace MinecraftClient.Mapping { Name = name ?? throw new ArgumentNullException(nameof(name)); - if (nbt == null) + if (nbt is null) throw new ArgumentNullException(nameof(nbt)); if (nbt.ContainsKey("piglin_safe")) diff --git a/MinecraftClient/Mapping/EntityPalettes/EntityPalette.cs b/MinecraftClient/Mapping/EntityPalettes/EntityPalette.cs index d1e30c16..0873d5d4 100644 --- a/MinecraftClient/Mapping/EntityPalettes/EntityPalette.cs +++ b/MinecraftClient/Mapping/EntityPalettes/EntityPalette.cs @@ -29,9 +29,9 @@ namespace MinecraftClient.Mapping.EntityPalettes Dictionary entityTypes = GetDict(); Dictionary? entityTypesNonLiving = GetDictNonLiving(); - if (entityTypesNonLiving != null && !living) + if (entityTypesNonLiving is not null && !living) { - //Pre-1.14 non-living entities have a different set of IDs (entityTypesNonLiving != null) + //Pre-1.14 non-living entities have a different set of IDs (entityTypesNonLiving is not null) if (entityTypesNonLiving.ContainsKey(id)) return entityTypesNonLiving[id]; } diff --git a/MinecraftClient/Mapping/Location.cs b/MinecraftClient/Mapping/Location.cs index a0bbbc35..abfda749 100644 --- a/MinecraftClient/Mapping/Location.cs +++ b/MinecraftClient/Mapping/Location.cs @@ -108,7 +108,7 @@ namespace MinecraftClient.Mapping public static Location Parse(string x, string y, string z) { Location.TryParse(x, y, z, out Location? res); - if (res == null) + if (res is null) throw new FormatException(); else return (Location)res; @@ -308,7 +308,7 @@ namespace MinecraftClient.Mapping /// TRUE if the locations are equals public override bool Equals(object? obj) { - if (obj == null) + if (obj is null) return false; if (obj is Location location) { diff --git a/MinecraftClient/Physics/BlockShapes.cs b/MinecraftClient/Physics/BlockShapes.cs index 2fbe5b27..b44c6816 100644 --- a/MinecraftClient/Physics/BlockShapes.cs +++ b/MinecraftClient/Physics/BlockShapes.cs @@ -39,7 +39,7 @@ namespace MinecraftClient.Physics /// public static Aabb[] GetShapes(int blockStateId) { - if (stateToShape != null && stateToShape.TryGetValue(blockStateId, out var shapes)) + if (stateToShape is not null && stateToShape.TryGetValue(blockStateId, out var shapes)) return shapes; return FallbackShape(blockStateId); } @@ -76,7 +76,7 @@ namespace MinecraftClient.Physics { var assembly = Assembly.GetExecutingAssembly(); using var stream = assembly.GetManifestResourceStream("BlockShapeData.json"); - if (stream == null) + if (stream is null) { ConsoleInteractive.ConsoleWriter.WriteLineFormatted("§e[Physics] BlockShapeData.json not found as embedded resource"); return; @@ -138,12 +138,12 @@ namespace MinecraftClient.Physics { stateToShape = new Dictionary(); - if (prismarineBlocks == null || prismarineShapes == null) + if (prismarineBlocks is null || prismarineShapes is null) return; var palette = Block.Palette; var dict = GetPaletteDict(palette); - if (dict == null) return; + if (dict is null) return; // Group consecutive state IDs by Material to find state ranges per block var materialRanges = new Dictionary>(); diff --git a/MinecraftClient/Protocol/Handlers/Protocol16.cs b/MinecraftClient/Protocol/Handlers/Protocol16.cs index 2e3a4e8a..21d2a488 100644 --- a/MinecraftClient/Protocol/Handlers/Protocol16.cs +++ b/MinecraftClient/Protocol/Handlers/Protocol16.cs @@ -251,7 +251,7 @@ namespace MinecraftClient.Protocol.Handlers /// Net read thread ID public int GetNetMainThreadId() { - return netRead != null ? netRead.Item1.ManagedThreadId : -1; + return netRead is not null ? netRead.Item1.ManagedThreadId : -1; } public bool SendCookieResponse(string name, byte[]? data) @@ -268,7 +268,7 @@ namespace MinecraftClient.Protocol.Handlers { try { - if (netRead != null) + if (netRead is not null) { netRead.Item2.Cancel(); c.Close(); @@ -556,7 +556,7 @@ namespace MinecraftClient.Protocol.Handlers string serverHash = CryptoHandler.GetServerHash(serverIDhash, serverPublicKey, secretKey); bool needCheckSession = true; - if (session.ServerPublicKey != null && session.SessionPreCheckTask != null + if (session.ServerPublicKey is not null && session.SessionPreCheckTask is not null && serverIDhash == session.ServerIDhash && Enumerable.SequenceEqual(serverPublicKey, session.ServerPublicKey)) { session.SessionPreCheckTask.Wait(); diff --git a/MinecraftClient/Protocol/Handlers/Protocol18Forge.cs b/MinecraftClient/Protocol/Handlers/Protocol18Forge.cs index dc1d6a12..3dbe753e 100644 --- a/MinecraftClient/Protocol/Handlers/Protocol18Forge.cs +++ b/MinecraftClient/Protocol/Handlers/Protocol18Forge.cs @@ -21,7 +21,7 @@ namespace MinecraftClient.Protocol.Handlers private readonly ForgeInfo? forgeInfo; private FMLHandshakeClientState fmlHandshakeState = FMLHandshakeClientState.START; - private bool ForgeEnabled() { return forgeInfo != null; } + private bool ForgeEnabled() { return forgeInfo is not null; } /// /// Initialize a new Forge protocol handler diff --git a/MinecraftClient/Protocol/Handlers/SocketWrapper.cs b/MinecraftClient/Protocol/Handlers/SocketWrapper.cs index e74fc84a..338bcd46 100644 --- a/MinecraftClient/Protocol/Handlers/SocketWrapper.cs +++ b/MinecraftClient/Protocol/Handlers/SocketWrapper.cs @@ -29,7 +29,7 @@ namespace MinecraftClient.Protocol.Handlers /// Silently dropped connection can only be detected by attempting to read/write data public bool IsConnected() { - return c.Client != null && c.Connected; + return c.Client is not null && c.Connected; } /// diff --git a/MinecraftClient/Protocol/Message/ChatMessage.cs b/MinecraftClient/Protocol/Message/ChatMessage.cs index 3088d85e..832fa19b 100644 --- a/MinecraftClient/Protocol/Message/ChatMessage.cs +++ b/MinecraftClient/Protocol/Message/ChatMessage.cs @@ -64,7 +64,7 @@ namespace MinecraftClient.Protocol.Message public LastSeenMessageList.AcknowledgedMessage? ToLastSeenMessageEntry() { - return signature != null ? new LastSeenMessageList.AcknowledgedMessage(senderUUID, signature, true) : null; + return signature is not null ? new LastSeenMessageList.AcknowledgedMessage(senderUUID, signature, true) : null; } public bool LacksSender() diff --git a/MinecraftClient/Protocol/Message/LastSeenMessageList.cs b/MinecraftClient/Protocol/Message/LastSeenMessageList.cs index 62b1227e..852095dc 100644 --- a/MinecraftClient/Protocol/Message/LastSeenMessageList.cs +++ b/MinecraftClient/Protocol/Message/LastSeenMessageList.cs @@ -107,7 +107,7 @@ namespace MinecraftClient.Protocol.Message } } - if (lastEntry != null && messageCount < acknowledgedMessages.Length) + if (lastEntry is not null && messageCount < acknowledgedMessages.Length) acknowledgedMessages[messageCount++] = lastEntry; LastSeenMessageList.AcknowledgedMessage[] msgList = new LastSeenMessageList.AcknowledgedMessage[messageCount]; @@ -120,7 +120,7 @@ namespace MinecraftClient.Protocol.Message { // net.minecraft.network.message.LastSeenMessagesCollector#add(net.minecraft.network.message.MessageSignatureData, boolean) // net.minecraft.network.message.LastSeenMessagesCollector#add(net.minecraft.network.message.AcknowledgedMessage) - if (lastEntry != null && entry.signature.SequenceEqual(lastEntry.signature)) + if (lastEntry is not null && entry.signature.SequenceEqual(lastEntry.signature)) return false; lastEntry = entry; @@ -143,7 +143,7 @@ namespace MinecraftClient.Protocol.Message { int k = (nextIndex + j) % acknowledgedMessages.Length; AcknowledgedMessage? acknowledgedMessage = acknowledgedMessages[k]; - if (acknowledgedMessage == null) + if (acknowledgedMessage is null) continue; bitset[j / 8] |= (byte)(1 << (j % 8)); // bitSet.set(j, true); objectList.Add(acknowledgedMessage); diff --git a/MinecraftClient/Protocol/ProfileKey/KeyUtils.cs b/MinecraftClient/Protocol/ProfileKey/KeyUtils.cs index bc2ad08f..381af81f 100644 --- a/MinecraftClient/Protocol/ProfileKey/KeyUtils.cs +++ b/MinecraftClient/Protocol/ProfileKey/KeyUtils.cs @@ -43,7 +43,7 @@ namespace MinecraftClient.Protocol.ProfileKey } catch (Exception e) { - int code = response == null ? 0 : response.StatusCode; + int code = response is null ? 0 : response.StatusCode; ConsoleIO.WriteLineFormatted("§cFetch authlib-injector metadata failed: HttpCode = " + code + ", Error = " + e.Message); if (Settings.Config.Logging.DebugMessages) ConsoleIO.WriteLineFormatted("§c" + e.StackTrace); @@ -93,12 +93,12 @@ namespace MinecraftClient.Protocol.ProfileKey } var json = Json.ParseJson(response.Body); - if (json?["keyPair"]?["publicKey"] == null - || json["keyPair"]?["privateKey"] == null - || json["publicKeySignature"] == null - || json["publicKeySignatureV2"] == null - || json["expiresAt"] == null - || json["refreshedAfter"] == null) + if (json?["keyPair"]?["publicKey"] is null + || json["keyPair"]?["privateKey"] is null + || json["publicKeySignature"] is null + || json["publicKeySignatureV2"] is null + || json["expiresAt"] is null + || json["refreshedAfter"] is null) { throw new InvalidOperationException("Certificate endpoint returned an unexpected payload."); } @@ -115,7 +115,7 @@ namespace MinecraftClient.Protocol.ProfileKey } catch (Exception e) { - int code = response == null ? 0 : response.StatusCode; + int code = response is null ? 0 : response.StatusCode; ConsoleIO.WriteLineFormatted("§cFetch profile key failed: HttpCode = " + code + ", Error = " + e.Message); if (Settings.Config.Logging.DebugMessages) ConsoleIO.WriteLineFormatted("§c" + e.StackTrace); @@ -209,7 +209,7 @@ namespace MinecraftClient.Protocol.ProfileKey { List data = new(); - if (precedingSignature != null) + if (precedingSignature is not null) data.AddRange(precedingSignature); data.AddRange(sender.ToBigEndianBytes()); diff --git a/MinecraftClient/Protocol/ProfileKey/PlayerKeyPair.cs b/MinecraftClient/Protocol/ProfileKey/PlayerKeyPair.cs index 572b0d06..2c1fc589 100644 --- a/MinecraftClient/Protocol/ProfileKey/PlayerKeyPair.cs +++ b/MinecraftClient/Protocol/ProfileKey/PlayerKeyPair.cs @@ -73,11 +73,11 @@ namespace MinecraftClient.Protocol.ProfileKey { List datas = new(); datas.Add(Convert.ToBase64String(PublicKey.Key)); - if (PublicKey.Signature == null) + if (PublicKey.Signature is null) datas.Add(string.Empty); else datas.Add(Convert.ToBase64String(PublicKey.Signature)); - if (PublicKey.SignatureV2 == null) + if (PublicKey.SignatureV2 is null) datas.Add(string.Empty); else datas.Add(Convert.ToBase64String(PublicKey.SignatureV2)); diff --git a/MinecraftClient/Protocol/ProfileKey/PublicKey.cs b/MinecraftClient/Protocol/ProfileKey/PublicKey.cs index 2208e04e..faa8ba33 100644 --- a/MinecraftClient/Protocol/ProfileKey/PublicKey.cs +++ b/MinecraftClient/Protocol/ProfileKey/PublicKey.cs @@ -25,10 +25,10 @@ namespace MinecraftClient.Protocol.ProfileKey if (!string.IsNullOrEmpty(sigV2)) SignatureV2 = Convert.FromBase64String(sigV2!); - if (SignatureV2 == null || SignatureV2.Length == 0) + if (SignatureV2 is null || SignatureV2.Length == 0) SignatureV2 = Signature; - if (Signature == null || Signature.Length == 0) + if (Signature is null || Signature.Length == 0) Signature = SignatureV2; } diff --git a/MinecraftClient/Protocol/Session/SessionToken.cs b/MinecraftClient/Protocol/Session/SessionToken.cs index 8687b99f..1364012b 100644 --- a/MinecraftClient/Protocol/Session/SessionToken.cs +++ b/MinecraftClient/Protocol/Session/SessionToken.cs @@ -45,7 +45,7 @@ namespace MinecraftClient.Protocol.Session public bool SessionPreCheck(LoginType type) { - if (ID == string.Empty || PlayerID == String.Empty || ServerPublicKey == null) + if (ID == string.Empty || PlayerID == String.Empty || ServerPublicKey is null) return false; Crypto.CryptoHandler.ClientAESPrivateKey ??= Crypto.CryptoHandler.GenerateAESPrivateKey(); string serverHash = Crypto.CryptoHandler.GetServerHash(ServerIDhash, ServerPublicKey, Crypto.CryptoHandler.ClientAESPrivateKey); @@ -57,7 +57,7 @@ namespace MinecraftClient.Protocol.Session public override string ToString() { return String.Join(",", ID, PlayerName, PlayerID, ClientID, RefreshToken, ServerIDhash, - (ServerPublicKey == null) ? String.Empty : Convert.ToBase64String(ServerPublicKey)); + (ServerPublicKey is null) ? String.Empty : Convert.ToBase64String(ServerPublicKey)); } public static SessionToken FromString(string tokenString) diff --git a/MinecraftClient/Scripting/DynamicRun/Builder/Compiler.cs b/MinecraftClient/Scripting/DynamicRun/Builder/Compiler.cs index 81417178..c941aa19 100644 --- a/MinecraftClient/Scripting/DynamicRun/Builder/Compiler.cs +++ b/MinecraftClient/Scripting/DynamicRun/Builder/Compiler.cs @@ -142,7 +142,7 @@ namespace MinecraftClient.Scripting.DynamicRun.Builder "[Script Error] Too many references to the same assembly. Assembly name: " + refs.Name); } - if (reference == null) { + if (reference is null) { throw new InvalidOperationException( "[Script Error] The executable does not contain a referenced assembly. Assembly name: " + refs.Name); } diff --git a/MinecraftClient/Settings.cs b/MinecraftClient/Settings.cs index 6ee9ecfd..2b11637e 100644 --- a/MinecraftClient/Settings.cs +++ b/MinecraftClient/Settings.cs @@ -1150,7 +1150,7 @@ namespace MinecraftClient break; default: - if (localVars != null && localVars.ContainsKey(varname_lower)) + if (localVars is not null && localVars.ContainsKey(varname_lower)) result.Append(localVars[varname_lower].ToString()); else if (TryGetVar(varname_lower, out object? var_value)) result.Append(var_value.ToString()); @@ -1979,7 +1979,7 @@ namespace MinecraftClient public static string GetFullMessage(this Exception ex) { string msg = ex.Message.Replace("+", "->"); - return ex.InnerException == null + return ex.InnerException is null ? msg : msg + "\n --> " + ex.InnerException.GetFullMessage(); }