Modernize null-check patterns: use 'is null' and 'is not null'

Replace '== null' with 'is null' and '!= null' with 'is not null'
across 19 core files following modern C# pattern matching conventions.

Only literal null comparisons are changed. Assignments, value
comparisons, and LINQ expressions are left untouched.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot] 2026-03-24 00:27:07 +00:00
parent 902e944cbb
commit c5df6a49c6
19 changed files with 111 additions and 111 deletions

View file

@ -474,7 +474,7 @@ namespace MinecraftClient.ChatBots
public override void OnEntityDespawn(Entity entity) public override void OnEntityDespawn(Entity entity)
{ {
if (entity != null && fishingBobber != null && entity.Type == EntityType.FishingBobber && entity.ID == fishingBobber!.ID) if (entity is not null && fishingBobber is not null && entity.Type == EntityType.FishingBobber && entity.ID == fishingBobber!.ID)
{ {
if (Config.Log_Fish_Bobber) if (Config.Log_Fish_Bobber)
LogToConsole(string.Format("FishingBobber despawn at {0}", entity.Location)); LogToConsole(string.Format("FishingBobber despawn at {0}", entity.Location));
@ -499,7 +499,7 @@ namespace MinecraftClient.ChatBots
public override void OnEntityMove(Entity entity) public override void OnEntityMove(Entity entity)
{ {
if (isFishing && entity != null && fishingBobber!.ID == entity.ID && if (isFishing && entity is not null && fishingBobber!.ID == entity.ID &&
(state == FishingState.WaitingFishToBite || state == FishingState.WaitingFishingBobber)) (state == FishingState.WaitingFishToBite || state == FishingState.WaitingFishingBobber))
{ {
Location Pos = entity.Location; Location Pos = entity.Location;
@ -603,12 +603,12 @@ namespace MinecraftClient.ChatBots
LocationConfig curConfig = locationList[curLocationIdx]; LocationConfig curConfig = locationList[curLocationIdx];
if (curConfig.facing != null) if (curConfig.facing is not null)
(nextYaw, nextPitch) = ((float)curConfig.facing.Value.yaw, (float)curConfig.facing.Value.pitch); (nextYaw, nextPitch) = ((float)curConfig.facing.Value.yaw, (float)curConfig.facing.Value.pitch);
else else
(nextYaw, nextPitch) = (GetYaw(), GetPitch()); (nextYaw, nextPitch) = (GetYaw(), GetPitch());
if (curConfig.XYZ != null) if (curConfig.XYZ is not null)
{ {
Location current = GetCurrentLocation(); Location current = GetCurrentLocation();
Location goal = new(curConfig.XYZ.Value.x, curConfig.XYZ.Value.y, curConfig.XYZ.Value.z); Location goal = new(curConfig.XYZ.Value.x, curConfig.XYZ.Value.y, curConfig.XYZ.Value.z);

View file

@ -132,7 +132,7 @@ namespace MinecraftClient.ChatBots
if (String.IsNullOrEmpty(toSend)) if (String.IsNullOrEmpty(toSend))
return null; return null;
if (regex != null) if (regex is not null)
{ {
if (regex.IsMatch(message)) if (regex.IsMatch(message))
{ {
@ -261,15 +261,15 @@ namespace MinecraftClient.ChatBots
/// <param name="cooldown">Minimal cooldown between two matches</param> /// <param name="cooldown">Minimal cooldown between two matches</param>
private void CheckAddMatch(Regex? matchRegex, string? matchString, string? matchAction, string? matchActionPrivate, string? matchActionOther, bool ownersOnly, TimeSpan cooldown) private void CheckAddMatch(Regex? matchRegex, string? matchString, string? matchAction, string? matchActionPrivate, string? matchActionOther, bool ownersOnly, TimeSpan cooldown)
{ {
if (matchRegex != null || matchString != null || matchAction != null || matchActionPrivate != null || matchActionOther != null || ownersOnly || cooldown != TimeSpan.Zero) if (matchRegex is not null || matchString is not null || matchAction is not null || matchActionPrivate is not null || matchActionOther is not null || ownersOnly || cooldown != TimeSpan.Zero)
{ {
RespondRule rule = matchRegex != null RespondRule rule = matchRegex is not null
? new RespondRule(matchRegex, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown) ? new RespondRule(matchRegex, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown)
: new RespondRule(matchString, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown); : new RespondRule(matchString, matchAction, matchActionPrivate, matchActionOther, ownersOnly, cooldown);
if (matchAction != null || matchActionPrivate != null || matchActionOther != null) if (matchAction is not null || matchActionPrivate is not null || matchActionOther is not null)
{ {
if (matchRegex != null || matchString != null) if (matchRegex is not null || matchString is not null)
{ {
respondRules!.Add(rule); respondRules!.Add(rule);
LogDebugToConsole(string.Format(Translations.bot_autoRespond_loaded_match, rule)); LogDebugToConsole(string.Format(Translations.bot_autoRespond_loaded_match, rule));

View file

@ -153,11 +153,11 @@ namespace MinecraftClient.ChatBots
private void Disconnect() private void Disconnect()
{ {
if (discordBotClient != null) if (discordBotClient is not null)
{ {
try try
{ {
if (discordChannel != null) if (discordChannel is not null)
discordBotClient.SendMessageAsync(discordChannel, new DiscordEmbedBuilder discordBotClient.SendMessageAsync(discordChannel, new DiscordEmbedBuilder
{ {
Description = Translations.bot_DiscordBridge_disconnected, Description = Translations.bot_DiscordBridge_disconnected,
@ -284,7 +284,7 @@ namespace MinecraftClient.ChatBots
filePath = filePath[(filePath.IndexOf(Path.DirectorySeparatorChar) + 1)..]; filePath = filePath[(filePath.IndexOf(Path.DirectorySeparatorChar) + 1)..];
var messageBuilder = new DiscordMessageBuilder(); var messageBuilder = new DiscordMessageBuilder();
if (text != null) if (text is not null)
messageBuilder.WithContent(text); messageBuilder.WithContent(text);
messageBuilder.AddFiles(new Dictionary<string, Stream>() { { filePath, fs } }); messageBuilder.AddFiles(new Dictionary<string, Stream>() { { filePath, fs } });
@ -309,7 +309,7 @@ namespace MinecraftClient.ChatBots
private bool CanSendMessages() private bool CanSendMessages()
{ {
return discordBotClient != null && discordChannel != null && bridgeDirection != BridgeDirection.Minecraft; return discordBotClient is not null && discordChannel is not null && bridgeDirection != BridgeDirection.Minecraft;
} }
async Task MainAsync() async Task MainAsync()

View file

@ -110,13 +110,13 @@ namespace MinecraftClient.ChatBots
&& !string.IsNullOrEmpty(entity.Name) && !string.IsNullOrEmpty(entity.Name)
&& entity.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); && entity.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (player == null) if (player is null)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_invalid_player); return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_invalid_player);
if (!CanMoveThere(player.Location)) if (!CanMoveThere(player.Location))
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_cant_reach_player); return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_cant_reach_player);
if (_playerToFollow != null && _playerToFollow.Equals(name, StringComparison.OrdinalIgnoreCase)) if (_playerToFollow is not null && _playerToFollow.Equals(name, StringComparison.OrdinalIgnoreCase))
return r.SetAndReturn(CmdResult.Status.Fail, return r.SetAndReturn(CmdResult.Status.Fail,
string.Format(Translations.cmd_follow_already_following, _playerToFollow)); string.Format(Translations.cmd_follow_already_following, _playerToFollow));
@ -127,7 +127,7 @@ namespace MinecraftClient.ChatBots
var result = var result =
string.Format( string.Format(
_playerToFollow != null ? Translations.cmd_follow_switched : Translations.cmd_follow_started, _playerToFollow is not null ? Translations.cmd_follow_switched : Translations.cmd_follow_started,
player.Name!); player.Name!);
_playerToFollow = name.ToLower(); _playerToFollow = name.ToLower();
@ -152,7 +152,7 @@ namespace MinecraftClient.ChatBots
private int OnCommandStop(CmdResult r) private int OnCommandStop(CmdResult r)
{ {
if (_playerToFollow == null) if (_playerToFollow is null)
return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_already_stopped); return r.SetAndReturn(CmdResult.Status.Fail, Translations.cmd_follow_already_stopped);
var movementLock = BotMovementLock.Instance; var movementLock = BotMovementLock.Instance;
@ -172,7 +172,7 @@ namespace MinecraftClient.ChatBots
if (entity.Type != EntityType.Player) if (entity.Type != EntityType.Player)
return; return;
if (_playerToFollow == null || string.IsNullOrEmpty(entity.Name)) if (_playerToFollow is null || string.IsNullOrEmpty(entity.Name))
return; return;
if (_playerToFollow != entity.Name.ToLower()) if (_playerToFollow != entity.Name.ToLower())
@ -200,7 +200,7 @@ namespace MinecraftClient.ChatBots
if (entity.Type != EntityType.Player) if (entity.Type != EntityType.Player)
return; return;
if (_playerToFollow != null && !string.IsNullOrEmpty(entity.Name) && if (_playerToFollow is not null && !string.IsNullOrEmpty(entity.Name) &&
_playerToFollow.Equals(entity.Name, StringComparison.OrdinalIgnoreCase)) _playerToFollow.Equals(entity.Name, StringComparison.OrdinalIgnoreCase))
{ {
LogToConsole(string.Format(Translations.cmd_follow_player_came_to_the_range, _playerToFollow)); LogToConsole(string.Format(Translations.cmd_follow_player_came_to_the_range, _playerToFollow));
@ -213,7 +213,7 @@ namespace MinecraftClient.ChatBots
if (entity.Type != EntityType.Player) if (entity.Type != EntityType.Player)
return; return;
if (_playerToFollow != null && !string.IsNullOrEmpty(entity.Name) && if (_playerToFollow is not null && !string.IsNullOrEmpty(entity.Name) &&
_playerToFollow.Equals(entity.Name, StringComparison.OrdinalIgnoreCase)) _playerToFollow.Equals(entity.Name, StringComparison.OrdinalIgnoreCase))
{ {
LogToConsole(string.Format(Translations.cmd_follow_player_left_the_range, _playerToFollow)); LogToConsole(string.Format(Translations.cmd_follow_player_left_the_range, _playerToFollow));
@ -223,7 +223,7 @@ namespace MinecraftClient.ChatBots
public override void OnPlayerLeave(Guid uuid, string? name) public override void OnPlayerLeave(Guid uuid, string? name)
{ {
if (_playerToFollow != null && !string.IsNullOrEmpty(name) && if (_playerToFollow is not null && !string.IsNullOrEmpty(name) &&
_playerToFollow.Equals(name, StringComparison.OrdinalIgnoreCase)) _playerToFollow.Equals(name, StringComparison.OrdinalIgnoreCase))
{ {
LogToConsole(string.Format(Translations.cmd_follow_player_left, _playerToFollow)); LogToConsole(string.Format(Translations.cmd_follow_player_left, _playerToFollow));
@ -235,7 +235,7 @@ namespace MinecraftClient.ChatBots
private bool CanMoveThere(Location location) private bool CanMoveThere(Location location)
{ {
var chunkColumn = GetWorld().GetChunkColumn(location); var chunkColumn = GetWorld().GetChunkColumn(location);
return chunkColumn != null && chunkColumn.FullyLoaded != false; return chunkColumn is not null && chunkColumn.FullyLoaded != false;
} }
} }
} }

View file

@ -260,20 +260,20 @@ namespace MinecraftClient.Commands
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_item}: {item.GetTypeString()} x{item.Count} - {displayName}§8"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_item}: {item.GetTypeString()} x{item.Count} - {displayName}§8");
} }
if (entity.Equipment.Count >= 1 && entity.Equipment != null) if (entity.Equipment is not null && entity.Equipment.Count >= 1)
{ {
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_equipment}:"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_equipment}:");
if (entity.Equipment.ContainsKey(0) && entity.Equipment[0] != null) if (entity.Equipment.ContainsKey(0) && entity.Equipment[0] is not null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_mainhand}: {entity.Equipment[0].GetTypeString()} x{entity.Equipment[0].Count}"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_mainhand}: {entity.Equipment[0].GetTypeString()} x{entity.Equipment[0].Count}");
if (entity.Equipment.ContainsKey(1) && entity.Equipment[1] != null) if (entity.Equipment.ContainsKey(1) && entity.Equipment[1] is not null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_offhand}: {entity.Equipment[1].GetTypeString()} x{entity.Equipment[1].Count}"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_offhand}: {entity.Equipment[1].GetTypeString()} x{entity.Equipment[1].Count}");
if (entity.Equipment.ContainsKey(5) && entity.Equipment[5] != null) if (entity.Equipment.ContainsKey(5) && entity.Equipment[5] is not null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_helmet}: {entity.Equipment[5].GetTypeString()} x{entity.Equipment[5].Count}"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_helmet}: {entity.Equipment[5].GetTypeString()} x{entity.Equipment[5].Count}");
if (entity.Equipment.ContainsKey(4) && entity.Equipment[4] != null) if (entity.Equipment.ContainsKey(4) && entity.Equipment[4] is not null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_chestplate}: {entity.Equipment[4].GetTypeString()} x{entity.Equipment[4].Count}"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_chestplate}: {entity.Equipment[4].GetTypeString()} x{entity.Equipment[4].Count}");
if (entity.Equipment.ContainsKey(3) && entity.Equipment[3] != null) if (entity.Equipment.ContainsKey(3) && entity.Equipment[3] is not null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_leggings}: {entity.Equipment[3].GetTypeString()} x{entity.Equipment[3].Count}"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_leggings}: {entity.Equipment[3].GetTypeString()} x{entity.Equipment[3].Count}");
if (entity.Equipment.ContainsKey(2) && entity.Equipment[2] != null) if (entity.Equipment.ContainsKey(2) && entity.Equipment[2] is not null)
sb.Append($"\n [MCC] {Translations.cmd_entityCmd_boots}: {entity.Equipment[2].GetTypeString()} x{entity.Equipment[2].Count}"); sb.Append($"\n [MCC] {Translations.cmd_entityCmd_boots}: {entity.Equipment[2].GetTypeString()} x{entity.Equipment[2].Count}");
} }

View file

@ -225,7 +225,7 @@ namespace MinecraftClient
sugList.Add(new("/")); sugList.Add(new("/"));
var childs = McClient.dispatcher.GetRoot().Children; var childs = McClient.dispatcher.GetRoot().Children;
if (childs != null) if (childs is not null)
foreach (var child in childs) foreach (var child in childs)
sugList.Add(new(child.Name)); sugList.Add(new(child.Name));
@ -247,7 +247,7 @@ namespace MinecraftClient
else else
{ {
CommandDispatcher<CmdResult>? dispatcher = McClient.dispatcher; CommandDispatcher<CmdResult>? dispatcher = McClient.dispatcher;
if (dispatcher == null) if (dispatcher is null)
return; return;
ParseResults<CmdResult> parse = dispatcher.Parse(command, CmdResult.Empty); ParseResults<CmdResult> parse = dispatcher.Parse(command, CmdResult.Empty);

View file

@ -82,20 +82,20 @@ namespace MinecraftClient.Inventory
{ {
get get
{ {
if (Components != null) if (Components is not null)
{ {
var customName = Components.OfType<CustomNameComponent>().FirstOrDefault(); var customName = Components.OfType<CustomNameComponent>().FirstOrDefault();
if (customName != null && !string.IsNullOrEmpty(customName.CustomName)) if (customName is not null && !string.IsNullOrEmpty(customName.CustomName))
return customName.CustomName; return customName.CustomName;
var itemName = Components.OfType<ItemNameComponent>().FirstOrDefault(); var itemName = Components.OfType<ItemNameComponent>().FirstOrDefault();
if (itemName != null && !string.IsNullOrEmpty(itemName.ItemName)) if (itemName is not null && !string.IsNullOrEmpty(itemName.ItemName))
return itemName.ItemName; return itemName.ItemName;
return null; return null;
} }
if (NBT != null && NBT.ContainsKey("display")) if (NBT is not null && NBT.ContainsKey("display"))
{ {
if (NBT["display"] is Dictionary<string, object> displayProperties && if (NBT["display"] is Dictionary<string, object> displayProperties &&
displayProperties.ContainsKey("Name")) displayProperties.ContainsKey("Name"))
@ -117,17 +117,17 @@ namespace MinecraftClient.Inventory
{ {
get get
{ {
if (Components != null) if (Components is not null)
{ {
var loreComponent = Components.OfType<LoreNameComponent1206>().FirstOrDefault(); var loreComponent = Components.OfType<LoreNameComponent1206>().FirstOrDefault();
if (loreComponent != null && loreComponent.Lines.Count > 0) if (loreComponent is not null && loreComponent.Lines.Count > 0)
return loreComponent.Lines.ToArray(); return loreComponent.Lines.ToArray();
return null; return null;
} }
List<string> lores = new(); List<string> lores = new();
if (NBT != null && NBT.ContainsKey("display")) if (NBT is not null && NBT.ContainsKey("display"))
{ {
if (NBT["display"] is Dictionary<string, object> displayProperties && if (NBT["display"] is Dictionary<string, object> displayProperties &&
displayProperties.ContainsKey("Lore")) displayProperties.ContainsKey("Lore"))
@ -151,19 +151,19 @@ namespace MinecraftClient.Inventory
{ {
get get
{ {
if (Components != null) if (Components is not null)
{ {
var damageComponent = Components.OfType<DamageComponent>().FirstOrDefault(); var damageComponent = Components.OfType<DamageComponent>().FirstOrDefault();
if (damageComponent != null) if (damageComponent is not null)
return damageComponent.Damage; return damageComponent.Damage;
return 0; return 0;
} }
if (NBT != null && NBT.ContainsKey("Damage")) if (NBT is not null && NBT.ContainsKey("Damage"))
{ {
object damage = NBT["Damage"]; object damage = NBT["Damage"];
if (damage != null) if (damage is not null)
{ {
return int.Parse(damage.ToString() ?? string.Empty, NumberStyles.Any, return int.Parse(damage.ToString() ?? string.Empty, NumberStyles.Any,
CultureInfo.CurrentCulture); CultureInfo.CurrentCulture);
@ -183,11 +183,11 @@ namespace MinecraftClient.Inventory
{ {
get get
{ {
if (Components == null) if (Components is null)
return null; return null;
var enchComp = Components.OfType<EnchantmentsComponent>().FirstOrDefault(); var enchComp = Components.OfType<EnchantmentsComponent>().FirstOrDefault();
if (enchComp != null && enchComp.Enchantments.Count > 0) if (enchComp is not null && enchComp.Enchantments.Count > 0)
return enchComp.Enchantments; return enchComp.Enchantments;
return null; return null;
@ -220,7 +220,7 @@ namespace MinecraftClient.Inventory
try try
{ {
var enchList = EnchantmentList; var enchList = EnchantmentList;
if (enchList != null) if (enchList is not null)
{ {
foreach (var ench in enchList) foreach (var ench in enchList)
{ {
@ -229,7 +229,7 @@ namespace MinecraftClient.Inventory
sb.AppendFormat(" | {0} {1}", name, level); sb.AppendFormat(" | {0} {1}", name, level);
} }
} }
else if (NBT != null && (NBT.TryGetValue("Enchantments", out object? enchantments) || else if (NBT is not null && (NBT.TryGetValue("Enchantments", out object? enchantments) ||
NBT.TryGetValue("StoredEnchantments", out enchantments))) NBT.TryGetValue("StoredEnchantments", out enchantments)))
{ {
foreach (Dictionary<string, object> enchantment in (object[])enchantments) foreach (Dictionary<string, object> enchantment in (object[])enchantments)
@ -242,7 +242,7 @@ namespace MinecraftClient.Inventory
} }
} }
if (Lores != null && Lores.Length > 0) if (Lores is not null && Lores.Length > 0)
{ {
foreach (var lore in Lores) foreach (var lore in Lores)
sb.AppendFormat(" | {0}", lore); sb.AppendFormat(" | {0}", lore);

View file

@ -38,9 +38,9 @@ namespace MinecraftClient.Inventory
// Condition: source has item and dest has no item // Condition: source has item and dest has no item
if (ValidateSlots(source, dest, destContainer) && if (ValidateSlots(source, dest, destContainer) &&
HasItem(source) && HasItem(source) &&
((destContainer != null && !HasItem(dest, destContainer)) || (destContainer == null && !HasItem(dest)))) ((destContainer is not null && !HasItem(dest, destContainer)) || (destContainer is null && !HasItem(dest))))
return mc.DoWindowAction(c.ID, source, WindowActionType.LeftClick) return mc.DoWindowAction(c.ID, source, WindowActionType.LeftClick)
&& mc.DoWindowAction(destContainer == null ? c.ID : destContainer.ID, dest, WindowActionType.LeftClick); && mc.DoWindowAction(destContainer is null ? c.ID : destContainer.ID, dest, WindowActionType.LeftClick);
else return false; else return false;
} }
@ -56,9 +56,9 @@ namespace MinecraftClient.Inventory
// Condition: Both slot1 and slot2 has item // Condition: Both slot1 and slot2 has item
if (ValidateSlots(slot1, slot2, destContainer) && if (ValidateSlots(slot1, slot2, destContainer) &&
HasItem(slot1) && HasItem(slot1) &&
(destContainer != null && HasItem(slot2, destContainer) || (destContainer == null && HasItem(slot2)))) (destContainer is not null && HasItem(slot2, destContainer) || (destContainer is null && HasItem(slot2))))
return mc.DoWindowAction(c.ID, slot1, WindowActionType.LeftClick) return mc.DoWindowAction(c.ID, slot1, WindowActionType.LeftClick)
&& mc.DoWindowAction(destContainer == null ? c.ID : destContainer.ID, slot2, WindowActionType.LeftClick) && mc.DoWindowAction(destContainer is null ? c.ID : destContainer.ID, slot2, WindowActionType.LeftClick)
&& mc.DoWindowAction(c.ID, slot1, WindowActionType.LeftClick); && mc.DoWindowAction(c.ID, slot1, WindowActionType.LeftClick);
else return false; else return false;
} }
@ -126,7 +126,7 @@ namespace MinecraftClient.Inventory
/// <returns>The compare result</returns> /// <returns>The compare result</returns>
private bool ValidateSlots(int s1, int s2, Container? s2Container = null) private bool ValidateSlots(int s1, int s2, Container? s2Container = null)
{ {
if (s2Container == null) if (s2Container is null)
return (s1 != s2 && s1 < c.Type.SlotCount() && s2 < c.Type.SlotCount()); return (s1 != s2 && s1 < c.Type.SlotCount() && s2 < c.Type.SlotCount());
else else
return (s1 < c.Type.SlotCount() && s2 < s2Container.Type.SlotCount()); return (s1 < c.Type.SlotCount() && s2 < s2Container.Type.SlotCount());
@ -153,7 +153,7 @@ namespace MinecraftClient.Inventory
/// <returns>True if they are equal</returns> /// <returns>True if they are equal</returns>
private bool ItemTypeEqual(int slot1, int slot2, Container? s2Container = null) private bool ItemTypeEqual(int slot1, int slot2, Container? s2Container = null)
{ {
if (s2Container == null) if (s2Container is null)
{ {
if (HasItem(slot1) && HasItem(slot2)) if (HasItem(slot1) && HasItem(slot2))
return c.Items[slot1].Type == c.Items[slot2].Type; return c.Items[slot1].Type == c.Items[slot2].Type;

View file

@ -247,7 +247,7 @@ namespace MinecraftClient.Mapping
} }
// Goal could not be reached. Set the path to the closest location if close enough // Goal could not be reached. Set the path to the closest location if close enough
if (current != null && openSet.MinHScoreNode != null && if (current is not null && openSet.MinHScoreNode is not null &&
(maxOffset == int.MaxValue || openSet.MinHScoreNode.HScore <= maxOffset)) (maxOffset == int.MaxValue || openSet.MinHScoreNode.HScore <= maxOffset))
return ReconstructPath(cameFrom, openSet.MinHScoreNode.Location, start, goal); return ReconstructPath(cameFrom, openSet.MinHScoreNode.Location, start, goal);
@ -362,7 +362,7 @@ namespace MinecraftClient.Mapping
locationList.Add(loc); locationList.Add(loc);
// Save node with the smallest H-Score => Distance to goal // Save node with the smallest H-Score => Distance to goal
if (MinHScoreNode == null || newNode.HScore < MinHScoreNode.HScore) if (MinHScoreNode is null || newNode.HScore < MinHScoreNode.HScore)
MinHScoreNode = newNode; MinHScoreNode = newNode;
if (i == 0) if (i == 0)
@ -491,7 +491,7 @@ namespace MinecraftClient.Mapping
public static bool IsOnGround(World world, Location location) public static bool IsOnGround(World world, Location location)
{ {
ChunkColumn? chunkColumn = world.GetChunkColumn(location); ChunkColumn? chunkColumn = world.GetChunkColumn(location);
if (chunkColumn == null || chunkColumn.FullyLoaded == false) if (chunkColumn is null || chunkColumn.FullyLoaded == false)
return true; // avoid moving downward in a not loaded chunk return true; // avoid moving downward in a not loaded chunk
Location down = Move(location, Direction.Down); Location down = Move(location, Direction.Down);
@ -721,11 +721,11 @@ namespace MinecraftClient.Mapping
public static bool CheckChunkLoading(World world, Location start, Location dest) public static bool CheckChunkLoading(World world, Location start, Location dest)
{ {
var chunkColumn = world.GetChunkColumn(dest); var chunkColumn = world.GetChunkColumn(dest);
if (chunkColumn == null || chunkColumn.FullyLoaded == false) if (chunkColumn is null || chunkColumn.FullyLoaded == false)
return false; return false;
chunkColumn = world.GetChunkColumn(start); chunkColumn = world.GetChunkColumn(start);
if (chunkColumn == null || chunkColumn.FullyLoaded == false) if (chunkColumn is null || chunkColumn.FullyLoaded == false)
return false; return false;
return true; return true;

View file

@ -55,7 +55,7 @@ namespace MinecraftClient.Mapping
set set
{ {
Tuple<int, int> chunkCoord = new(chunkX, chunkZ); Tuple<int, int> chunkCoord = new(chunkX, chunkZ);
if (value == null) if (value is null)
chunks.TryRemove(chunkCoord, out _); chunks.TryRemove(chunkCoord, out _);
else else
chunks.AddOrUpdate(chunkCoord, value, (_, _) => value); chunks.AddOrUpdate(chunkCoord, value, (_, _) => value);
@ -385,10 +385,10 @@ namespace MinecraftClient.Mapping
public Block GetBlock(Location location) public Block GetBlock(Location location)
{ {
ChunkColumn? column = GetChunkColumn(location); ChunkColumn? column = GetChunkColumn(location);
if (column != null) if (column is not null)
{ {
Chunk? chunk = column.GetChunk(location); Chunk? chunk = column.GetChunk(location);
if (chunk != null) if (chunk is not null)
return chunk.GetBlock(location); return chunk.GetBlock(location);
} }
return Block.Air; return Block.Air;
@ -437,10 +437,10 @@ namespace MinecraftClient.Mapping
public void SetBlock(Location location, Block block) public void SetBlock(Location location, Block block)
{ {
ChunkColumn? column = this[location.ChunkX, location.ChunkZ]; ChunkColumn? column = this[location.ChunkX, location.ChunkZ];
if (column != null && column.ColumnSize >= location.ChunkY) if (column is not null && column.ColumnSize >= location.ChunkY)
{ {
Chunk? chunk = column.GetChunk(location); Chunk? chunk = column.GetChunk(location);
if (chunk == null) if (chunk is null)
column[location.ChunkY] = chunk = new Chunk(); column[location.ChunkY] = chunk = new Chunk();
chunk[location.ChunkBlockX, location.ChunkBlockY, location.ChunkBlockZ] = block; chunk[location.ChunkBlockX, location.ChunkBlockY, location.ChunkBlockZ] = block;
} }

View file

@ -120,7 +120,7 @@ namespace MinecraftClient
ConsoleIO.WriteLine($"Minecraft Console Client v{Version} - for MC {MCLowestVersion} to {MCHighestVersion} - Github.com/MCCTeam"); ConsoleIO.WriteLine($"Minecraft Console Client v{Version} - for MC {MCLowestVersion} to {MCHighestVersion} - Github.com/MCCTeam");
//Build information to facilitate processing of bug reports //Build information to facilitate processing of bug reports
if (BuildInfo != null) if (BuildInfo is not null)
ConsoleIO.WriteLineFormatted("§8" + BuildInfo); ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
//Debug input ? //Debug input ?
@ -616,11 +616,11 @@ namespace MinecraftClient
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.mcc_profile_key_valid, session.PlayerName)); ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.mcc_profile_key_valid, session.PlayerName));
} }
if (playerKeyPair == null || playerKeyPair.NeedRefresh()) if (playerKeyPair is null || playerKeyPair.NeedRefresh())
{ {
ConsoleIO.WriteLineFormatted(Translations.mcc_fetching_key, acceptnewlines: true); ConsoleIO.WriteLineFormatted(Translations.mcc_fetching_key, acceptnewlines: true);
playerKeyPair = KeyUtils.GetNewProfileKeys(session.ID, Config.Main.General.AccountType == LoginType.yggdrasil); playerKeyPair = KeyUtils.GetNewProfileKeys(session.ID, Config.Main.General.AccountType == LoginType.yggdrasil);
if (Config.Main.Advanced.ProfileKeyCache != CacheType.none && playerKeyPair != null) if (Config.Main.Advanced.ProfileKeyCache != CacheType.none && playerKeyPair is not null)
{ {
KeysCache.Store(loginLower, playerKeyPair); KeysCache.Store(loginLower, playerKeyPair);
} }
@ -628,7 +628,7 @@ namespace MinecraftClient
} }
//Force-enable Forge support? //Force-enable Forge support?
if (!isRealms && (Config.Main.Advanced.EnableForge == ForgeConfigType.force) && forgeInfo == null) if (!isRealms && (Config.Main.Advanced.EnableForge == ForgeConfigType.force) && forgeInfo is null)
{ {
if (ProtocolHandler.ProtocolMayForceForge(protocolversion)) if (ProtocolHandler.ProtocolMayForceForge(protocolversion))
{ {
@ -724,8 +724,8 @@ namespace MinecraftClient
ConsoleInteractive.ConsoleReader.StopReadThread(); ConsoleInteractive.ConsoleReader.StopReadThread();
new Thread(new ThreadStart(delegate new Thread(new ThreadStart(delegate
{ {
if (client != null) { client.Disconnect(); ConsoleIO.Reset(); } if (client is not null) { client.Disconnect(); ConsoleIO.Reset(); }
if (offlinePrompt != null) { offlinePrompt.Item2.Cancel(); offlinePrompt.Item1.Join(); offlinePrompt = null; ConsoleIO.Reset(); } if (offlinePrompt is not null) { offlinePrompt.Item2.Cancel(); offlinePrompt.Item1.Join(); offlinePrompt = null; ConsoleIO.Reset(); }
if (delaySeconds > 0) if (delaySeconds > 0)
{ {
ConsoleIO.WriteLine(string.Format(Translations.mcc_restart_delay, delaySeconds)); ConsoleIO.WriteLine(string.Format(Translations.mcc_restart_delay, delaySeconds));
@ -743,8 +743,8 @@ namespace MinecraftClient
ConsoleInteractive.ConsoleSuggestion.ClearSuggestions(); ConsoleInteractive.ConsoleSuggestion.ClearSuggestions();
ConsoleIO.WriteLineFormatted("§a" + string.Format(Translations.config_saving, settingsIniPath)); ConsoleIO.WriteLineFormatted("§a" + string.Format(Translations.config_saving, settingsIniPath));
if (client != null) { client.Disconnect(); ConsoleIO.Reset(); } if (client is not null) { client.Disconnect(); ConsoleIO.Reset(); }
if (offlinePrompt != null) { offlinePrompt.Item2.Cancel(); offlinePrompt.Item1.Join(); offlinePrompt = null; ConsoleIO.Reset(); } if (offlinePrompt is not null) { offlinePrompt.Item2.Cancel(); offlinePrompt.Item1.Join(); offlinePrompt = null; ConsoleIO.Reset(); }
if (Config.Main.Advanced.PlayerHeadAsIcon) { ConsoleIcon.RevertToMCCIcon(); } if (Config.Main.Advanced.PlayerHeadAsIcon) { ConsoleIcon.RevertToMCCIcon(); }
Environment.Exit(exitcode); Environment.Exit(exitcode);
} }
@ -801,7 +801,7 @@ namespace MinecraftClient
return; //AutoRelog is triggering a restart of the client, don't turn on the offline prompt return; //AutoRelog is triggering a restart of the client, don't turn on the offline prompt
} }
if (offlinePrompt == null) if (offlinePrompt is null)
{ {
ConsoleInteractive.ConsoleReader.StopReadThread(); ConsoleInteractive.ConsoleReader.StopReadThread();
@ -907,7 +907,7 @@ namespace MinecraftClient
/// <returns></returns> /// <returns></returns>
public static Type[] GetTypesInNamespace(string nameSpace, Assembly? assembly = null) public static Type[] GetTypesInNamespace(string nameSpace, Assembly? assembly = null)
{ {
if (assembly == null) { assembly = Assembly.GetExecutingAssembly(); } if (assembly is null) { assembly = Assembly.GetExecutingAssembly(); }
return assembly.GetTypes().Where(t => string.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray(); return assembly.GetTypes().Where(t => string.Equals(t.Namespace, nameSpace, StringComparison.Ordinal)).ToArray();
} }

View file

@ -1350,7 +1350,7 @@ namespace MinecraftClient.Protocol.Handlers
/// <returns>Byte array for this NBT tag</returns> /// <returns>Byte array for this NBT tag</returns>
private byte[] GetNbt(Dictionary<string, object>? nbt, bool root) private byte[] GetNbt(Dictionary<string, object>? nbt, bool root)
{ {
if (nbt == null || nbt.Count == 0) if (nbt is null || nbt.Count == 0)
return new byte[] { 0 }; // TAG_End return new byte[] { 0 }; // TAG_End
List<byte> bytes = new(); List<byte> bytes = new();
@ -1699,7 +1699,7 @@ namespace MinecraftClient.Protocol.Handlers
{ {
List<byte> slotData = new(); List<byte> slotData = new();
if (item == null || item.IsEmpty) if (item is null || item.IsEmpty)
{ {
slotData.AddRange(GetBool(false)); slotData.AddRange(GetBool(false));
} }
@ -1727,7 +1727,7 @@ namespace MinecraftClient.Protocol.Handlers
if (protocolversion >= Protocol18Handler.MC_1_20_6_Version) if (protocolversion >= Protocol18Handler.MC_1_20_6_Version)
{ {
if (item == null || item.IsEmpty) if (item is null || item.IsEmpty)
{ {
slotData.AddRange(GetVarInt(0)); slotData.AddRange(GetVarInt(0));
} }
@ -1736,7 +1736,7 @@ namespace MinecraftClient.Protocol.Handlers
slotData.AddRange(GetVarInt(item.Count)); slotData.AddRange(GetVarInt(item.Count));
slotData.AddRange(GetVarInt(itemPalette.ToId(item.Type))); slotData.AddRange(GetVarInt(itemPalette.ToId(item.Type)));
if (item.Components != null && item.Components.Count > 0) if (item.Components is not null && item.Components.Count > 0)
{ {
slotData.AddRange(GetVarInt(item.Components.Count)); slotData.AddRange(GetVarInt(item.Components.Count));
slotData.AddRange(GetVarInt(0)); // components to remove slotData.AddRange(GetVarInt(0)); // components to remove
@ -1756,7 +1756,7 @@ namespace MinecraftClient.Protocol.Handlers
} }
else if (protocolversion > Protocol18Handler.MC_1_13_Version) else if (protocolversion > Protocol18Handler.MC_1_13_Version)
{ {
if (item == null || item.IsEmpty) if (item is null || item.IsEmpty)
slotData.AddRange(GetBool(false)); slotData.AddRange(GetBool(false));
else else
{ {
@ -1768,7 +1768,7 @@ namespace MinecraftClient.Protocol.Handlers
} }
else else
{ {
if (item == null || item.IsEmpty) if (item is null || item.IsEmpty)
slotData.AddRange(GetShort(-1)); slotData.AddRange(GetShort(-1));
else else
{ {
@ -1849,7 +1849,7 @@ namespace MinecraftClient.Protocol.Handlers
/// <returns>String representation</returns> /// <returns>String representation</returns>
public string ByteArrayToString(byte[]? bytes) public string ByteArrayToString(byte[]? bytes)
{ {
if (bytes == null) if (bytes is null)
return "null"; return "null";
else else
return BitConverter.ToString(bytes).Replace("-", " "); return BitConverter.ToString(bytes).Replace("-", " ");
@ -1890,7 +1890,7 @@ namespace MinecraftClient.Protocol.Handlers
{ {
List<byte> fields = new(); List<byte> fields = new();
fields.AddRange(GetLastSeenMessageList(ack.lastSeen, isOnlineMode)); fields.AddRange(GetLastSeenMessageList(ack.lastSeen, isOnlineMode));
if (!isOnlineMode || ack.lastReceived == null) if (!isOnlineMode || ack.lastReceived is null)
fields.AddRange(GetBool(false)); // Has last received message fields.AddRange(GetBool(false)); // Has last received message
else else
{ {

View file

@ -123,7 +123,7 @@ namespace MinecraftClient.Protocol.Message
{ {
string sender = message.isSenderJson ? ParseText(message.displayName!) : message.displayName!; string sender = message.isSenderJson ? ParseText(message.displayName!) : message.displayName!;
string content; string content;
if (Config.Signature.ShowModifiedChat && message.unsignedContent != null) if (Config.Signature.ShowModifiedChat && message.unsignedContent is not null)
{ {
content = ParseText(message.unsignedContent!); content = ParseText(message.unsignedContent!);
if (string.IsNullOrEmpty(content)) if (string.IsNullOrEmpty(content))
@ -315,7 +315,7 @@ namespace MinecraftClient.Protocol.Message
Task<Dictionary<string, string>?> fetckFileTask = Task<Dictionary<string, string>?> fetckFileTask =
httpClient.GetFromJsonAsync<Dictionary<string, string>>(translation_file_location); httpClient.GetFromJsonAsync<Dictionary<string, string>>(translation_file_location);
fetckFileTask.Wait(); fetckFileTask.Wait();
if (fetckFileTask.Result != null && fetckFileTask.Result.Count > 0) if (fetckFileTask.Result is not null && fetckFileTask.Result.Count > 0)
{ {
TranslationRules = fetckFileTask.Result; TranslationRules = fetckFileTask.Result;
TranslationRules["Version"] = TranslationsFile_Version; TranslationRules["Version"] = TranslationsFile_Version;

View file

@ -44,13 +44,13 @@ namespace MinecraftClient.Protocol
{ {
Uuid = uuid; Uuid = uuid;
Name = name; Name = name;
if (property != null) if (property is not null)
Property = property; Property = property;
Gamemode = gamemode; Gamemode = gamemode;
Ping = ping; Ping = ping;
DisplayName = displayName; DisplayName = displayName;
lastMessageVerified = false; lastMessageVerified = false;
if (timeStamp != null && publicKey != null && signature != null) if (timeStamp is not null && publicKey is not null && signature is not null)
{ {
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds((long)timeStamp); DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds((long)timeStamp);
KeyExpiresAt = dateTimeOffset.UtcDateTime; KeyExpiresAt = dateTimeOffset.UtcDateTime;
@ -119,7 +119,7 @@ namespace MinecraftClient.Protocol
/// <returns>Is this message vaild</returns> /// <returns>Is this message vaild</returns>
public bool VerifyMessage(string message, long timestamp, long salt, ref byte[] signature) public bool VerifyMessage(string message, long timestamp, long salt, ref byte[] signature)
{ {
if (PublicKey == null || IsKeyExpired()) if (PublicKey is null || IsKeyExpired())
return false; return false;
else else
{ {
@ -146,12 +146,12 @@ namespace MinecraftClient.Protocol
{ {
if (lastMessageVerified == false) if (lastMessageVerified == false)
return false; return false;
if (PublicKey == null || IsKeyExpired() || (this.precedingSignature != null && precedingSignature == null)) if (PublicKey is null || IsKeyExpired() || (this.precedingSignature is not null && precedingSignature is null))
{ {
lastMessageVerified = false; lastMessageVerified = false;
return false; return false;
} }
if (this.precedingSignature != null && !this.precedingSignature.SequenceEqual(precedingSignature!)) if (this.precedingSignature is not null && !this.precedingSignature.SequenceEqual(precedingSignature!))
{ {
lastMessageVerified = false; lastMessageVerified = false;
return false; return false;
@ -181,12 +181,12 @@ namespace MinecraftClient.Protocol
{ {
if (lastMessageVerified == false) if (lastMessageVerified == false)
return false; return false;
if (PublicKey == null || IsKeyExpired() || (this.precedingSignature != null && precedingSignature == null)) if (PublicKey is null || IsKeyExpired() || (this.precedingSignature is not null && precedingSignature is null))
{ {
lastMessageVerified = false; lastMessageVerified = false;
return false; return false;
} }
if (this.precedingSignature != null && !this.precedingSignature.SequenceEqual(precedingSignature!)) if (this.precedingSignature is not null && !this.precedingSignature.SequenceEqual(precedingSignature!))
{ {
lastMessageVerified = false; lastMessageVerified = false;
return false; return false;
@ -212,7 +212,7 @@ namespace MinecraftClient.Protocol
/// <returns>Is this message chain vaild</returns> /// <returns>Is this message chain vaild</returns>
public bool VerifyMessage(string message, Guid playerUuid, Guid chatUuid, int messageIndex, long timestamp, long salt, ref byte[] signature, Tuple<int, byte[]?>[] previousMessageSignatures) public bool VerifyMessage(string message, Guid playerUuid, Guid chatUuid, int messageIndex, long timestamp, long salt, ref byte[] signature, Tuple<int, byte[]?>[] previousMessageSignatures)
{ {
if (PublicKey == null || IsKeyExpired()) if (PublicKey is null || IsKeyExpired())
return false; return false;
// net.minecraft.server.network.ServerPlayNetworkHandler#validateMessage // net.minecraft.server.network.ServerPlayNetworkHandler#validateMessage

View file

@ -925,7 +925,7 @@ namespace MinecraftClient.Protocol
int code = DoHTTPSPost("authserver.mojang.com", 443, "/refresh", json_request, ref result); int code = DoHTTPSPost("authserver.mojang.com", 443, "/refresh", json_request, ref result);
if (code == 200) if (code == 200)
{ {
if (result == null) if (result is null)
{ {
return LoginResult.NullError; return LoginResult.NullError;
} }
@ -976,7 +976,7 @@ namespace MinecraftClient.Protocol
Config.Main.General.AuthServer.UseHttps, ref result); Config.Main.General.AuthServer.UseHttps, ref result);
if (code == 200) if (code == 200)
{ {
if (result == null) if (result is null)
{ {
return LoginResult.NullError; return LoginResult.NullError;
} }
@ -1251,7 +1251,7 @@ namespace MinecraftClient.Protocol
contentType = header.Value; contentType = header.Value;
} }
if (body != null) if (body is not null)
request.Content = new StringContent(body, Encoding.UTF8, contentType); request.Content = new StringContent(body, Encoding.UTF8, contentType);
if (Settings.Config.Logging.DebugMessages) if (Settings.Config.Logging.DebugMessages)
@ -1279,9 +1279,9 @@ namespace MinecraftClient.Protocol
} }
} }
}, TimeSpan.FromSeconds(30)); }, TimeSpan.FromSeconds(30));
if (postResult != null) if (postResult is not null)
result = postResult; result = postResult;
if (exception != null) if (exception is not null)
throw exception; throw exception;
return statusCode; return statusCode;
} }

View file

@ -109,7 +109,7 @@ namespace MinecraftClient.Scripting
var result = compiler.Compile(code, Guid.NewGuid().ToString(), dlls); var result = compiler.Compile(code, Guid.NewGuid().ToString(), dlls);
//Process compile warnings and errors //Process compile warnings and errors
if (result.Failures != null) if (result.Failures is not null)
{ {
ConsoleIO.WriteLogLine("[Script] Compilation failed with error(s):"); ConsoleIO.WriteLogLine("[Script] Compilation failed with error(s):");
@ -309,7 +309,7 @@ namespace MinecraftClient.Scripting
/// <returns>Value of the variable or null if no variable</returns> /// <returns>Value of the variable or null if no variable</returns>
public object? GetVar(string varName) public object? GetVar(string varName)
{ {
if (localVars != null && localVars.ContainsKey(varName)) if (localVars is not null && localVars.ContainsKey(varName))
return localVars[varName]; return localVars[varName];
else else
return Config.AppVar.GetVar(varName); return Config.AppVar.GetVar(varName);
@ -322,7 +322,7 @@ namespace MinecraftClient.Scripting
/// <param name="varValue">Value of the variable</param> /// <param name="varValue">Value of the variable</param>
public bool SetVar(string varName, object varValue) public bool SetVar(string varName, object varValue)
{ {
if (localVars != null && localVars.ContainsKey(varName)) if (localVars is not null && localVars.ContainsKey(varName))
localVars.Remove(varName); localVars.Remove(varName);
return Config.AppVar.SetVar(varName, varValue); return Config.AppVar.SetVar(varName, varValue);
} }
@ -339,12 +339,12 @@ namespace MinecraftClient.Scripting
object? value = GetVar(varName); object? value = GetVar(varName);
if (value is T Tval) if (value is T Tval)
return Tval; return Tval;
if (value != null) if (value is not null)
{ {
try try
{ {
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null) if (converter is not null)
return (T?)converter.ConvertFromString(value.ToString() ?? string.Empty); return (T?)converter.ConvertFromString(value.ToString() ?? string.Empty);
} }
catch (NotSupportedException) { /* Was worth trying */ } catch (NotSupportedException) { /* Was worth trying */ }

View file

@ -49,9 +49,9 @@ namespace MinecraftClient.Scripting
{ {
get get
{ {
if (master != null) if (master is not null)
return master.Handler; return master.Handler;
if (_handler != null) if (_handler is not null)
return _handler; return _handler;
throw new InvalidOperationException(Translations.exception_chatbot_init); throw new InvalidOperationException(Translations.exception_chatbot_init);
} }
@ -862,7 +862,7 @@ namespace MinecraftClient.Scripting
protected void LogToConsole(object? text) protected void LogToConsole(object? text)
{ {
string botName = Translations.ResourceManager.GetString("botname." + GetType().Name) ?? GetType().Name; string botName = Translations.ResourceManager.GetString("botname." + GetType().Name) ?? GetType().Name;
if (_handler == null || master == null) if (_handler is null || master is null)
ConsoleIO.WriteLogLine(string.Format("[{0}] {1}", botName, text)); ConsoleIO.WriteLogLine(string.Format("[{0}] {1}", botName, text));
else else
Handler.Log.Info(string.Format("[{0}] {1}", botName, text)); Handler.Log.Info(string.Format("[{0}] {1}", botName, text));

View file

@ -113,7 +113,7 @@ namespace MinecraftClient
} }
// Receive exception from task // Receive exception from task
if (exception != null) if (exception is not null)
throw exception; throw exception;
return result!; return result!;

View file

@ -211,7 +211,7 @@ namespace MinecraftClient
if (!cancellationToken.IsCancellationRequested) if (!cancellationToken.IsCancellationRequested)
{ {
HttpResponseMessage res = httpWebRequest.Result; HttpResponseMessage res = httpWebRequest.Result;
if (res.Headers.Location != null) if (res.Headers.Location is not null)
{ {
Match match = Regex.Match(res.Headers.Location.ToString(), GithubReleaseUrl + @"/tag/(\d{4})(\d{2})(\d{2})-(\d+)"); Match match = Regex.Match(res.Headers.Location.ToString(), GithubReleaseUrl + @"/tag/(\d{4})(\d{2})(\d{2})-(\d+)");
if (match.Success && match.Groups.Count == 5) if (match.Success && match.Groups.Count == 5)
@ -284,7 +284,7 @@ namespace MinecraftClient
private static bool CompareVersionInfo(string? current, string? latest) private static bool CompareVersionInfo(string? current, string? latest)
{ {
if (current == null || latest == null) if (current is null || latest is null)
return false; return false;
Regex reg = new(@"\w+\sbuild\s(\d+),\sbuilt\son\s(\d{4})[-\/\.\s]?(\d{2})[-\/\.\s]?(\d{2}).*"); Regex reg = new(@"\w+\sbuild\s(\d+),\sbuilt\son\s(\d{4})[-\/\.\s]?(\d{2})[-\/\.\s]?(\d{2}).*");
Regex reg2 = new(@"\w+\sbuild\s(\d+),\sbuilt\son\s\w+\s(\d{2})[-\/\.\s]?(\d{2})[-\/\.\s]?(\d{4}).*"); Regex reg2 = new(@"\w+\sbuild\s(\d+),\sbuilt\son\s\w+\s(\d{2})[-\/\.\s]?(\d{2})[-\/\.\s]?(\d{4}).*");
@ -297,13 +297,13 @@ namespace MinecraftClient
try { curTime = new(int.Parse(curMatch.Groups[2].Value), int.Parse(curMatch.Groups[3].Value), int.Parse(curMatch.Groups[4].Value)); } try { curTime = new(int.Parse(curMatch.Groups[2].Value), int.Parse(curMatch.Groups[3].Value), int.Parse(curMatch.Groups[4].Value)); }
catch { curTime = null; } catch { curTime = null; }
} }
if (curTime == null) if (curTime is null)
{ {
curMatch = reg2.Match(current); curMatch = reg2.Match(current);
try { curTime = new(int.Parse(curMatch.Groups[4].Value), int.Parse(curMatch.Groups[3].Value), int.Parse(curMatch.Groups[2].Value)); } try { curTime = new(int.Parse(curMatch.Groups[4].Value), int.Parse(curMatch.Groups[3].Value), int.Parse(curMatch.Groups[2].Value)); }
catch { curTime = null; } catch { curTime = null; }
} }
if (curTime == null) if (curTime is null)
return false; return false;
Match latestMatch = reg.Match(latest); Match latestMatch = reg.Match(latest);
@ -312,13 +312,13 @@ namespace MinecraftClient
try { latestTime = new(int.Parse(latestMatch.Groups[2].Value), int.Parse(latestMatch.Groups[3].Value), int.Parse(latestMatch.Groups[4].Value)); } try { latestTime = new(int.Parse(latestMatch.Groups[2].Value), int.Parse(latestMatch.Groups[3].Value), int.Parse(latestMatch.Groups[4].Value)); }
catch { latestTime = null; } catch { latestTime = null; }
} }
if (latestTime == null) if (latestTime is null)
{ {
latestMatch = reg2.Match(latest); latestMatch = reg2.Match(latest);
try { latestTime = new(int.Parse(latestMatch.Groups[4].Value), int.Parse(latestMatch.Groups[3].Value), int.Parse(latestMatch.Groups[2].Value)); } try { latestTime = new(int.Parse(latestMatch.Groups[4].Value), int.Parse(latestMatch.Groups[3].Value), int.Parse(latestMatch.Groups[2].Value)); }
catch { latestTime = null; } catch { latestTime = null; }
} }
if (latestTime == null) if (latestTime is null)
return false; return false;
int curBuildId, latestBuildId; int curBuildId, latestBuildId;