From 10676be3771165e9c87c9d464d07aee0e4c73f10 Mon Sep 17 00:00:00 2001 From: teinarss Date: Sat, 24 Apr 2021 17:46:24 +0200 Subject: [PATCH] Replace F extension with string interpolation --- OpenRA.Game/Activities/Activity.cs | 4 +- OpenRA.Game/Actor.cs | 8 +-- OpenRA.Game/CPos.cs | 8 +-- OpenRA.Game/CVec.cs | 6 +-- OpenRA.Game/Exts.cs | 8 +-- OpenRA.Game/FieldLoader.cs | 8 +-- OpenRA.Game/FieldSaver.cs | 2 +- OpenRA.Game/FileFormats/Png.cs | 2 +- OpenRA.Game/FileFormats/ReplayMetadata.cs | 2 +- OpenRA.Game/FileSystem/FileSystem.cs | 6 +-- OpenRA.Game/Game.cs | 10 ++-- OpenRA.Game/GameInformation.cs | 4 +- OpenRA.Game/GameRules/ActorInfo.cs | 5 +- OpenRA.Game/GameRules/Ruleset.cs | 6 +-- OpenRA.Game/GameSpeed.cs | 2 +- OpenRA.Game/Graphics/CursorManager.cs | 2 +- OpenRA.Game/Graphics/CursorProvider.cs | 2 +- OpenRA.Game/Graphics/HardwarePalette.cs | 8 +-- OpenRA.Game/Graphics/ModelRenderer.cs | 2 +- OpenRA.Game/Graphics/SequenceProvider.cs | 8 +-- OpenRA.Game/Graphics/SheetBuilder.cs | 2 +- OpenRA.Game/Graphics/SpriteFont.cs | 2 +- OpenRA.Game/Graphics/SpriteRenderer.cs | 4 +- OpenRA.Game/Graphics/Util.cs | 4 +- OpenRA.Game/Input/Hotkey.cs | 2 +- OpenRA.Game/InstalledMods.cs | 2 +- OpenRA.Game/Manifest.cs | 4 +- OpenRA.Game/Map/ActorInitializer.cs | 2 +- OpenRA.Game/Map/ActorReference.cs | 10 ++-- OpenRA.Game/Map/Map.cs | 14 ++--- OpenRA.Game/Map/MapPlayers.cs | 6 +-- OpenRA.Game/Map/MapPreview.cs | 2 +- OpenRA.Game/MiniYaml.cs | 19 ++++--- OpenRA.Game/ModData.cs | 8 +-- OpenRA.Game/Network/Connection.cs | 14 +++-- OpenRA.Game/Network/ConnectionTarget.cs | 2 +- OpenRA.Game/Network/FrameData.cs | 2 +- OpenRA.Game/Network/GameSave.cs | 4 +- OpenRA.Game/Network/GameServer.cs | 6 +-- OpenRA.Game/Network/Order.cs | 8 ++- OpenRA.Game/Network/OrderManager.cs | 4 +- OpenRA.Game/Network/ReplayRecorder.cs | 5 +- OpenRA.Game/Network/Session.cs | 12 ++--- OpenRA.Game/Network/SyncReport.cs | 6 +-- OpenRA.Game/Network/UnitOrders.cs | 2 +- OpenRA.Game/ObjectCreator.cs | 8 +-- OpenRA.Game/Platform.cs | 6 +-- OpenRA.Game/Player.cs | 8 +-- OpenRA.Game/Primitives/Rectangle.cs | 2 +- OpenRA.Game/Primitives/Size.cs | 2 +- .../Primitives/SpatiallyPartitioned.cs | 2 +- OpenRA.Game/Primitives/TypeDictionary.cs | 4 +- OpenRA.Game/Primitives/float3.cs | 2 +- OpenRA.Game/Renderer.cs | 8 +-- OpenRA.Game/Scripting/ScriptActorInterface.cs | 4 +- OpenRA.Game/Scripting/ScriptContext.cs | 10 ++-- OpenRA.Game/Scripting/ScriptMemberExts.cs | 12 ++--- OpenRA.Game/Scripting/ScriptMemberWrapper.cs | 10 ++-- .../Scripting/ScriptPlayerInterface.cs | 4 +- OpenRA.Game/Scripting/ScriptTypes.cs | 4 +- OpenRA.Game/Server/Server.cs | 16 +++--- OpenRA.Game/Settings.cs | 4 +- OpenRA.Game/Sound/Sound.cs | 4 +- OpenRA.Game/StreamExts.cs | 2 +- OpenRA.Game/Support/Benchmark.cs | 4 +- OpenRA.Game/Support/Evaluator.cs | 2 +- OpenRA.Game/Support/Log.cs | 4 +- OpenRA.Game/Support/VariableExpression.cs | 52 ++++++++----------- OpenRA.Game/Sync.cs | 4 +- OpenRA.Game/TraitDictionary.cs | 6 +-- OpenRA.Game/Traits/Player/FrozenActorLayer.cs | 2 +- OpenRA.Game/Traits/World/ScreenMap.cs | 2 +- OpenRA.Game/Translation.cs | 4 +- OpenRA.Game/WAngle.cs | 12 ++--- OpenRA.Game/WDist.cs | 2 +- OpenRA.Game/WPos.cs | 8 +-- OpenRA.Game/WVec.cs | 6 +-- OpenRA.Game/Widgets/Widget.cs | 8 ++- OpenRA.Game/Widgets/WidgetLoader.cs | 4 +- OpenRA.Mods.Cnc/Activities/Teleport.cs | 2 +- OpenRA.Mods.Cnc/FileFormats/HvaReader.cs | 3 +- OpenRA.Mods.Cnc/FileFormats/IdxEntry.cs | 2 +- OpenRA.Mods.Cnc/FileFormats/IdxReader.cs | 4 +- OpenRA.Mods.Cnc/FileFormats/LCWCompression.cs | 4 +- OpenRA.Mods.Cnc/FileFormats/VqaReader.cs | 10 ++-- OpenRA.Mods.Cnc/FileSystem/MixFile.cs | 8 +-- OpenRA.Mods.Cnc/FileSystem/PackageEntry.cs | 6 +-- .../Graphics/ClassicSpriteSequence.cs | 3 +- OpenRA.Mods.Cnc/Graphics/Voxel.cs | 6 +-- .../Graphics/VoxelModelSequenceLoader.cs | 6 +-- .../Properties/ChronosphereProperties.cs | 3 +- .../Properties/InfiltrateProperties.cs | 2 +- .../SpriteLoaders/ShpRemasteredLoader.cs | 6 +-- OpenRA.Mods.Cnc/SpriteLoaders/ShpTDLoader.cs | 2 +- OpenRA.Mods.Cnc/Traits/EnergyWall.cs | 2 +- OpenRA.Mods.Cnc/Traits/MadTank.cs | 4 +- OpenRA.Mods.Cnc/Traits/Minelayer.cs | 16 +++--- .../Traits/SupportPowers/DropPodsPower.cs | 2 +- .../Traits/SupportPowers/IonCannonPower.cs | 2 +- .../Traits/World/TSVeinsRenderer.cs | 2 +- .../ImportRedAlertLegacyMapCommand.cs | 2 +- .../UtilityCommands/ImportTSMapCommand.cs | 8 +-- .../ImportTiberianDawnLegacyMapCommand.cs | 2 +- .../UtilityCommands/LegacyTilesetImporter.cs | 40 +++++++------- .../EditorBrushes/EditorActorBrush.cs | 2 +- .../EditorBrushes/EditorCopyPasteBrush.cs | 2 +- .../EditorBrushes/EditorDefaultBrush.cs | 4 +- .../EditorBrushes/EditorResourceBrush.cs | 2 +- .../EditorBrushes/EditorTileBrush.cs | 4 +- OpenRA.Mods.Common/Effects/FloatingText.cs | 2 +- .../InstallShieldCABCompression.cs | 6 +-- OpenRA.Mods.Common/FileFormats/WavReader.cs | 2 +- .../Graphics/DefaultSpriteSequence.cs | 33 +++++------- .../Lint/CheckActorReferences.cs | 12 ++--- OpenRA.Mods.Common/Lint/CheckActors.cs | 2 +- OpenRA.Mods.Common/Lint/CheckAngle.cs | 10 ++-- OpenRA.Mods.Common/Lint/CheckChromeHotkeys.cs | 6 +-- OpenRA.Mods.Common/Lint/CheckChromeLogic.cs | 4 +- OpenRA.Mods.Common/Lint/CheckConditions.cs | 4 +- .../Lint/CheckConflictingMouseBounds.cs | 2 +- OpenRA.Mods.Common/Lint/CheckCursors.cs | 2 +- .../Lint/CheckDefaultVisibility.cs | 8 +-- OpenRA.Mods.Common/Lint/CheckHitShapes.cs | 2 +- .../Lint/CheckLocomotorReferences.cs | 4 +- OpenRA.Mods.Common/Lint/CheckMapMetadata.cs | 2 +- OpenRA.Mods.Common/Lint/CheckMapTiles.cs | 2 +- OpenRA.Mods.Common/Lint/CheckNotifications.cs | 3 +- OpenRA.Mods.Common/Lint/CheckOwners.cs | 6 +-- OpenRA.Mods.Common/Lint/CheckPalettes.cs | 8 +-- OpenRA.Mods.Common/Lint/CheckPlayers.cs | 14 ++--- OpenRA.Mods.Common/Lint/CheckRangeLimit.cs | 3 +- .../Lint/CheckRevealFootprint.cs | 4 +- OpenRA.Mods.Common/Lint/CheckSequences.cs | 12 ++--- OpenRA.Mods.Common/Lint/CheckSpriteBodies.cs | 2 +- .../Lint/CheckSyncAnnotations.cs | 4 +- OpenRA.Mods.Common/Lint/CheckTraitLocation.cs | 2 +- .../Lint/CheckTraitPrerequisites.cs | 4 +- .../Lint/CheckUnknownTraitFields.cs | 8 +-- .../Lint/CheckUnknownWeaponFields.cs | 12 ++--- .../Lint/CheckVoiceReferences.cs | 2 +- .../Lint/CheckWorldAndPlayerInherits.cs | 2 +- .../Lint/LintBuildablePrerequisites.cs | 2 +- OpenRA.Mods.Common/Lint/LintExts.cs | 6 +-- .../LoadScreens/BlankLoadScreen.cs | 2 +- .../Scripting/Global/ActorGlobal.cs | 22 ++++---- .../Scripting/Global/ReinforcementsGlobal.cs | 2 +- .../Scripting/Global/TriggerGlobal.cs | 2 +- .../Properties/AmmoPoolProperties.cs | 6 +-- .../Scripting/Properties/CaptureProperties.cs | 2 +- .../Properties/ConditionProperties.cs | 2 +- .../Properties/DeliveryProperties.cs | 2 +- .../Scripting/Properties/GeneralProperties.cs | 6 +-- .../Properties/PlayerConditionProperties.cs | 2 +- .../Scripting/Properties/PlayerProperties.cs | 6 +-- .../Properties/ProductionProperties.cs | 6 +-- .../ServerTraits/LobbyCommands.cs | 28 +++++----- .../ServerTraits/PlayerPinger.cs | 2 +- OpenRA.Mods.Common/SpriteLoaders/DdsLoader.cs | 2 +- .../SpriteLoaders/PngSheetLoader.cs | 4 +- OpenRA.Mods.Common/SpriteLoaders/TgaLoader.cs | 2 +- OpenRA.Mods.Common/Terrain/DefaultTerrain.cs | 4 +- .../Terrain/DefaultTileCache.cs | 3 +- OpenRA.Mods.Common/Terrain/TerrainInfo.cs | 8 +-- OpenRA.Mods.Common/Traits/Air/FallsToEarth.cs | 2 +- OpenRA.Mods.Common/Traits/Armament.cs | 4 +- .../BotModuleLogic/BaseBuilderQueueManager.cs | 2 +- .../Traits/BotModules/HarvesterBotModule.cs | 2 +- OpenRA.Mods.Common/Traits/Buildings/Bridge.cs | 2 +- .../Traits/Buildings/Building.cs | 4 +- .../FootprintPlaceBuildingPreview.cs | 4 +- .../Traits/Buildings/GroundLevelBridge.cs | 2 +- .../Traits/Buildings/Reservable.cs | 3 +- .../Traits/Buildings/TransformsIntoMobile.cs | 4 +- OpenRA.Mods.Common/Traits/CashTrickler.cs | 2 +- .../Traits/CombatDebugOverlay.cs | 2 +- .../Conditions/GrantConditionOnHealth.cs | 2 +- OpenRA.Mods.Common/Traits/Explodes.cs | 4 +- .../Traits/ExplosionOnDamageTransition.cs | 2 +- OpenRA.Mods.Common/Traits/HitShape.cs | 2 +- OpenRA.Mods.Common/Traits/Mobile.cs | 4 +- .../Traits/Player/DeveloperMode.cs | 4 +- .../Traits/Player/TimeLimitManager.cs | 2 +- OpenRA.Mods.Common/Traits/PowerTooltip.cs | 2 +- .../Traits/Render/ProductionBar.cs | 2 +- .../Traits/Render/RenderDebugState.cs | 2 +- .../Traits/Render/WithNameTagDecoration.cs | 2 +- .../Render/WithTextControlGroupDecoration.cs | 2 +- .../Traits/Render/WithTextDecoration.cs | 2 +- .../Traits/SupportPowers/NukePower.cs | 2 +- .../Traits/SupportPowers/ParatroopersPower.cs | 2 +- OpenRA.Mods.Common/Traits/ThrowsShrapnel.cs | 2 +- .../Traits/World/ActorSpawnManager.cs | 6 +-- .../Traits/World/CreateMapPlayers.cs | 2 +- .../Traits/World/DomainIndex.cs | 2 +- .../Traits/World/EditorActorLayer.cs | 4 +- .../Traits/World/EditorActorPreview.cs | 6 +-- .../Traits/World/ExitsDebugOverlayManager.cs | 2 +- .../Traits/World/IndexedPalette.cs | 2 +- .../Traits/World/IndexedPlayerPalette.cs | 2 +- OpenRA.Mods.Common/Traits/World/MapOptions.cs | 2 +- .../Traits/World/PaletteFromGimpOrJascFile.cs | 10 ++-- .../Traits/World/PaletteFromPng.cs | 2 +- .../Traits/World/SpawnStartingUnits.cs | 4 +- .../Traits/World/TerrainRenderer.cs | 4 +- .../Rules/20200202/AddResourceRenderer.cs | 4 +- .../20200202/CreateScreenShakeWarhead.cs | 6 +-- .../Rules/20200202/ReformatChromeProvider.cs | 4 +- .../20200202/RemoveWithPermanentInjury.cs | 2 +- .../UpdateRules/Rules/20200202/RenameSpins.cs | 2 +- .../Rules/20200503/AddPipDecorationTraits.cs | 16 +++--- .../ConvertSupportPowerRangesToFootprint.cs | 2 +- .../CreateFlashPaletteEffectWarhead.cs | 4 +- .../20200503/ModernizeDecorationTraits.cs | 2 +- .../Rules/20200503/MoveClassicFacingFudge.cs | 2 +- .../Rules/20200503/RemoveLaysTerrain.cs | 2 +- .../20200503/RemoveMuzzleSplitFacings.cs | 7 +-- .../Rules/20200503/SplitDamagedByTerrain.cs | 4 +- .../Rules/20200503/UpdateMapInits.cs | 4 +- .../20201213/RemovePlaceBuildingPalette.cs | 2 +- .../20201213/RemoveRenderSpritesScale.cs | 4 +- .../20201213/RemoveSmokeTrailWhenDamaged.cs | 2 +- .../Rules/20201213/ReplaceShadowPalette.cs | 6 +-- .../ReplaceWithColoredOverlayPalette.cs | 2 +- OpenRA.Mods.Common/UpdateRules/UpdateUtils.cs | 2 +- OpenRA.Mods.Common/Util.cs | 13 +++-- ...CheckConditionalTraitInterfaceOverrides.cs | 2 +- .../UtilityCommands/CheckMissingSprites.cs | 6 +-- .../UtilityCommands/CheckYaml.cs | 16 +++--- .../ConvertSpriteToPngCommand.cs | 2 +- .../UtilityCommands/CreateManPage.cs | 4 +- .../UtilityCommands/DebugChromeRegions.cs | 4 +- .../DumpSequenceSheetsCommand.cs | 6 +-- .../UtilityCommands/ExtractFilesCommand.cs | 2 +- .../UtilityCommands/ExtractLuaDocsCommand.cs | 6 +-- .../ExtractTraitDocsCommand.cs | 10 ++-- .../ExtractWeaponDocsCommand.cs | 6 +-- .../ExtractZeroBraneStudioLuaAPI.cs | 2 +- .../UtilityCommands/ImportLegacyMapCommand.cs | 10 ++-- .../UtilityCommands/ReplayMetadataCommand.cs | 2 +- .../UtilityCommands/ResizeMapCommand.cs | 2 +- .../Warheads/FireClusterWarhead.cs | 2 +- .../Warheads/LeaveSmudgeWarhead.cs | 2 +- OpenRA.Mods.Common/Widgets/ImageWidget.cs | 2 +- OpenRA.Mods.Common/Widgets/LabelWidget.cs | 2 +- .../Widgets/Logic/AssetBrowserLogic.cs | 5 +- .../Widgets/Logic/ButtonTooltipLogic.cs | 2 +- .../Widgets/Logic/ColorPickerLogic.cs | 6 +-- .../Widgets/Logic/ConnectionLogic.cs | 8 ++- .../Widgets/Logic/DirectConnectLogic.cs | 2 +- .../Widgets/Logic/Editor/ActorEditLogic.cs | 2 +- .../Widgets/Logic/Editor/MapEditorLogic.cs | 5 +- .../Widgets/Logic/GameSaveBrowserLogic.cs | 10 ++-- .../Widgets/Logic/Ingame/DebugLogic.cs | 2 +- .../Logic/Ingame/GameInfoStatsLogic.cs | 8 +-- .../Widgets/Logic/Ingame/GameTimerLogic.cs | 6 +-- .../Logic/Ingame/IngameCashCounterLogic.cs | 2 +- .../Ingame/ObserverShroudSelectorLogic.cs | 2 +- .../Logic/Ingame/ProductionTooltipLogic.cs | 2 +- .../Logic/Ingame/SupportPowerTooltipLogic.cs | 4 +- .../Installation/DownloadPackageLogic.cs | 6 +-- .../Installation/InstallFromDiscLogic.cs | 16 +++--- .../Installation/ModContentPromptLogic.cs | 2 +- .../Widgets/Logic/IntroductionPromptLogic.cs | 2 +- .../Widgets/Logic/Lobby/KickClientLogic.cs | 2 +- .../Logic/Lobby/KickSpectatorsLogic.cs | 2 +- .../Widgets/Logic/Lobby/LobbyLogic.cs | 10 ++-- .../Widgets/Logic/Lobby/LobbyOptionsLogic.cs | 4 +- .../Widgets/Logic/Lobby/LobbyUtils.cs | 38 +++++++------- .../Widgets/Logic/Lobby/MapPreviewLogic.cs | 10 ++-- .../Logic/Lobby/SpawnSelectorTooltipLogic.cs | 2 +- .../Widgets/Logic/MainMenuLogic.cs | 4 +- .../Widgets/Logic/MapChooserLogic.cs | 8 +-- .../Widgets/Logic/MissionBrowserLogic.cs | 6 +-- .../Widgets/Logic/MusicPlayerLogic.cs | 4 +- .../Widgets/Logic/PerfDebugLogic.cs | 5 +- .../Widgets/Logic/ReplayBrowserLogic.cs | 8 +-- .../Widgets/Logic/ReplayUtils.cs | 2 +- .../Widgets/Logic/ServerCreationLogic.cs | 6 +-- .../Widgets/Logic/ServerListLogic.cs | 15 +++--- .../Logic/Settings/DisplaySettingsLogic.cs | 10 ++-- .../Widgets/Logic/Settings/SettingsLogic.cs | 2 +- .../Widgets/Logic/Settings/SettingsUtils.cs | 6 +-- .../Widgets/Logic/SystemInfoPromptLogic.cs | 4 +- .../Widgets/ProductionPaletteWidget.cs | 2 +- .../Widgets/StrategicProgressWidget.cs | 4 +- .../Widgets/SupportPowersWidget.cs | 2 +- .../Widgets/ViewportControllerWidget.cs | 4 +- OpenRA.Mods.Common/Widgets/WidgetUtils.cs | 6 +-- OpenRA.Mods.D2k/Lint/CheckImportActors.cs | 2 +- OpenRA.Mods.D2k/SpriteLoaders/R8Loader.cs | 2 +- .../Traits/World/D2kResourceRenderer.cs | 2 +- .../UtilityCommands/D2kMapImporter.cs | 6 +-- OpenRA.Platforms.Default/FrameBuffer.cs | 4 +- OpenRA.Platforms.Default/OpenGL.cs | 6 +-- .../Sdl2GraphicsContext.cs | 2 +- .../Sdl2HardwareCursor.cs | 4 +- .../Sdl2PlatformWindow.cs | 2 +- OpenRA.Platforms.Default/Shader.cs | 4 +- OpenRA.Platforms.Default/Texture.cs | 6 +-- OpenRA.Utility/Program.cs | 2 +- 300 files changed, 752 insertions(+), 799 deletions(-) diff --git a/OpenRA.Game/Activities/Activity.cs b/OpenRA.Game/Activities/Activity.cs index 0fa330a896..6a94b8a4cd 100644 --- a/OpenRA.Game/Activities/Activity.cs +++ b/OpenRA.Game/Activities/Activity.cs @@ -95,7 +95,7 @@ namespace OpenRA.Activities public Activity TickOuter(Actor self) { if (State == ActivityState.Done) - throw new InvalidOperationException("Actor {0} attempted to tick activity {1} after it had already completed.".F(self, GetType())); + throw new InvalidOperationException($"Actor {self} attempted to tick activity {GetType()} after it had already completed."); if (State == ActivityState.Queued) { @@ -105,7 +105,7 @@ namespace OpenRA.Activities } if (!firstRunCompleted) - throw new InvalidOperationException("Actor {0} attempted to tick activity {1} before running its OnFirstRun method.".F(self, GetType())); + throw new InvalidOperationException($"Actor {self} attempted to tick activity {GetType()} before running its OnFirstRun method."); // Only run the parent tick when the child is done. // We must always let the child finish on its own before continuing. diff --git a/OpenRA.Game/Actor.cs b/OpenRA.Game/Actor.cs index fc84eaa999..d3d805aa7b 100644 --- a/OpenRA.Game/Actor.cs +++ b/OpenRA.Game/Actor.cs @@ -125,7 +125,7 @@ namespace OpenRA .FirstOrDefault(i => i.Count() > 1); if (duplicateInit != null) - throw new InvalidDataException("Duplicate initializer '{0}'".F(duplicateInit.Key.Name)); + throw new InvalidDataException($"Duplicate initializer '{duplicateInit.Key.Name}'"); var init = new ActorInitializer(this, initDict); @@ -250,7 +250,7 @@ namespace OpenRA continue; if (creationActivity != null) - throw new InvalidOperationException("More than one enabled ICreationActivity trait: {0} and {1}".F(creationActivity.GetType().Name, ica.GetType().Name)); + throw new InvalidOperationException($"More than one enabled ICreationActivity trait: {creationActivity.GetType().Name} and {ica.GetType().Name}"); var activity = ica.GetCreationActivity(); if (activity == null) @@ -592,7 +592,7 @@ namespace OpenRA public int RevokeCondition(int token) { if (!conditionTokens.TryGetValue(token, out var condition)) - throw new InvalidOperationException("Attempting to revoke condition with invalid token {0} for {1}.".F(token, this)); + throw new InvalidOperationException($"Attempting to revoke condition with invalid token {token} for {this}."); conditionTokens.Remove(token); UpdateConditionState(condition, token, true); @@ -632,7 +632,7 @@ namespace OpenRA public LuaValue ToString(LuaRuntime runtime) { - return "Actor ({0})".F(this); + return $"Actor ({this})"; } public bool HasScriptProperty(string name) diff --git a/OpenRA.Game/CPos.cs b/OpenRA.Game/CPos.cs index 9ef4afaa98..40f82e3a2e 100644 --- a/OpenRA.Game/CPos.cs +++ b/OpenRA.Game/CPos.cs @@ -90,7 +90,7 @@ namespace OpenRA public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out CPos a) || !right.TryGetClrValue(out CVec b)) - throw new LuaException("Attempted to call CPos.Add(CPos, CVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call CPos.Add(CPos, CVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); return new LuaCustomClrObject(a + b); } @@ -99,7 +99,7 @@ namespace OpenRA { var rightType = right.WrappedClrType(); if (!left.TryGetClrValue(out CPos a)) - throw new LuaException("Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); + throw new LuaException($"Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})"); if (rightType == typeof(CPos)) { @@ -112,7 +112,7 @@ namespace OpenRA return new LuaCustomClrObject(a - b); } - throw new LuaException("Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); + throw new LuaException($"Attempted to call CPos.Subtract(CPos, (CPos|CVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})"); } public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) @@ -132,7 +132,7 @@ namespace OpenRA case "X": return X; case "Y": return Y; case "Layer": return Layer; - default: throw new LuaException("CPos does not define a member '{0}'".F(key)); + default: throw new LuaException($"CPos does not define a member '{key}'"); } } diff --git a/OpenRA.Game/CVec.cs b/OpenRA.Game/CVec.cs index ee7e721eb8..d5fe3ad415 100644 --- a/OpenRA.Game/CVec.cs +++ b/OpenRA.Game/CVec.cs @@ -76,7 +76,7 @@ namespace OpenRA public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out CVec a) || !right.TryGetClrValue(out CVec b)) - throw new LuaException("Attempted to call CVec.Add(CVec, CVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call CVec.Add(CVec, CVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); return new LuaCustomClrObject(a + b); } @@ -84,7 +84,7 @@ namespace OpenRA public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out CVec a) || !right.TryGetClrValue(out CVec b)) - throw new LuaException("Attempted to call CVec.Subtract(CVec, CVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call CVec.Subtract(CVec, CVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); return new LuaCustomClrObject(a - b); } @@ -110,7 +110,7 @@ namespace OpenRA { case "X": return X; case "Y": return Y; - default: throw new LuaException("CVec does not define a member '{0}'".F(key)); + default: throw new LuaException($"CVec does not define a member '{key}'"); } } diff --git a/OpenRA.Game/Exts.cs b/OpenRA.Game/Exts.cs index 2f1e49c844..c16bb7ae01 100644 --- a/OpenRA.Game/Exts.cs +++ b/OpenRA.Game/Exts.cs @@ -278,7 +278,7 @@ namespace OpenRA public static int ISqrt(int number, ISqrtRoundMode round = ISqrtRoundMode.Floor) { if (number < 0) - throw new InvalidOperationException("Attempted to calculate the square root of a negative integer: {0}".F(number)); + throw new InvalidOperationException($"Attempted to calculate the square root of a negative integer: {number}"); return (int)ISqrt((uint)number, round); } @@ -319,7 +319,7 @@ namespace OpenRA public static long ISqrt(long number, ISqrtRoundMode round = ISqrtRoundMode.Floor) { if (number < 0) - throw new InvalidOperationException("Attempted to calculate the square root of a negative integer: {0}".F(number)); + throw new InvalidOperationException($"Attempted to calculate the square root of a negative integer: {number}"); return (long)ISqrt((ulong)number, round); } @@ -429,8 +429,8 @@ namespace OpenRA // If any duplicates were found, throw a descriptive error if (dupKeys.Count > 0) { - var badKeysFormatted = string.Join(", ", dupKeys.Select(p => "{0}: [{1}]".F(logKey(p.Key), string.Join(",", p.Value)))); - var msg = "{0}, duplicate values found for the following keys: {1}".F(debugName, badKeysFormatted); + var badKeysFormatted = string.Join(", ", dupKeys.Select(p => $"{logKey(p.Key)}: [{string.Join(",", p.Value)}]")); + var msg = $"{debugName}, duplicate values found for the following keys: {badKeysFormatted}"; throw new ArgumentException(msg); } diff --git a/OpenRA.Game/FieldLoader.cs b/OpenRA.Game/FieldLoader.cs index 0510d8e548..212558ed22 100644 --- a/OpenRA.Game/FieldLoader.cs +++ b/OpenRA.Game/FieldLoader.cs @@ -58,12 +58,12 @@ namespace OpenRA public static Func InvalidValueAction = (s, t, f) => { - throw new YamlException("FieldLoader: Cannot parse `{0}` into `{1}.{2}` ".F(s, f, t)); + throw new YamlException($"FieldLoader: Cannot parse `{s}` into `{f}.{t}` "); }; public static Action UnknownFieldAction = (s, f) => { - throw new NotImplementedException("FieldLoader: Missing field `{0}` on `{1}`".F(s, f.Name)); + throw new NotImplementedException($"FieldLoader: Missing field `{s}` on `{f.Name}`"); }; static readonly ConcurrentCache TypeLoadInfo = @@ -660,7 +660,7 @@ namespace OpenRA } } - UnknownFieldAction("[Type] {0}".F(value), fieldType); + UnknownFieldAction($"[Type] {value}", fieldType); return null; } @@ -771,7 +771,7 @@ namespace OpenRA { var method = type.GetMethod(Loader, Flags); if (method == null) - throw new InvalidOperationException("{0} does not specify a loader function '{1}'".F(type.Name, Loader)); + throw new InvalidOperationException($"{type.Name} does not specify a loader function '{Loader}'"); return (Func)Delegate.CreateDelegate(typeof(Func), method); } diff --git a/OpenRA.Game/FieldSaver.cs b/OpenRA.Game/FieldSaver.cs index 6f1774b178..4bd28e9a91 100644 --- a/OpenRA.Game/FieldSaver.cs +++ b/OpenRA.Game/FieldSaver.cs @@ -94,7 +94,7 @@ namespace OpenRA var formattedKey = FormatValue(key); var formattedValue = FormatValue(value); - result += "{0}: {1}{2}".F(formattedKey, formattedValue, Environment.NewLine); + result += $"{formattedKey}: {formattedValue}{Environment.NewLine}"; } return result; diff --git a/OpenRA.Game/FileFormats/Png.cs b/OpenRA.Game/FileFormats/Png.cs index 2bb4f2c552..405609dede 100644 --- a/OpenRA.Game/FileFormats/Png.cs +++ b/OpenRA.Game/FileFormats/Png.cs @@ -213,7 +213,7 @@ namespace OpenRA.FileFormats } default: - throw new InvalidDataException("Unhandled SpriteFrameType {0}".F(type)); + throw new InvalidDataException($"Unhandled SpriteFrameType {type}"); } if (embeddedData != null) diff --git a/OpenRA.Game/FileFormats/ReplayMetadata.cs b/OpenRA.Game/FileFormats/ReplayMetadata.cs index 9d4d37f2aa..9428babbe5 100644 --- a/OpenRA.Game/FileFormats/ReplayMetadata.cs +++ b/OpenRA.Game/FileFormats/ReplayMetadata.cs @@ -44,7 +44,7 @@ namespace OpenRA.FileFormats // Read version var version = fs.ReadInt32(); if (version != MetaVersion) - throw new NotSupportedException("Metadata version {0} is not supported".F(version)); + throw new NotSupportedException($"Metadata version {version} is not supported"); // Read game info (max 100K limit as a safeguard against corrupted files) var data = fs.ReadString(Encoding.UTF8, 1024 * 100); diff --git a/OpenRA.Game/FileSystem/FileSystem.cs b/OpenRA.Game/FileSystem/FileSystem.cs index 16ebe4c613..e7dea93f3d 100644 --- a/OpenRA.Game/FileSystem/FileSystem.cs +++ b/OpenRA.Game/FileSystem/FileSystem.cs @@ -95,7 +95,7 @@ namespace OpenRA.FileSystem name = name.Substring(1); if (!installedMods.TryGetValue(name, out var mod)) - throw new InvalidOperationException("Could not load mod '{0}'. Available mods: {1}".F(name, installedMods.Keys.JoinWith(", "))); + throw new InvalidOperationException($"Could not load mod '{name}'. Available mods: {installedMods.Keys.JoinWith(", ")}"); package = mod.Package; modPackages.Add(package); @@ -104,7 +104,7 @@ namespace OpenRA.FileSystem { package = OpenPackage(name); if (package == null) - throw new InvalidOperationException("Could not open package '{0}', file not found or its format is not supported.".F(name)); + throw new InvalidOperationException($"Could not open package '{name}', file not found or its format is not supported."); } Mount(package, explicitName); @@ -203,7 +203,7 @@ namespace OpenRA.FileSystem public Stream Open(string filename) { if (!TryOpen(filename, out var s)) - throw new FileNotFoundException("File not found: {0}".F(filename), filename); + throw new FileNotFoundException($"File not found: {filename}", filename); return s; } diff --git a/OpenRA.Game/Game.cs b/OpenRA.Game/Game.cs index d5fcf952bc..a37f932592 100644 --- a/OpenRA.Game/Game.cs +++ b/OpenRA.Game/Game.cs @@ -216,7 +216,7 @@ namespace OpenRA var orders = new[] { - Order.Command("sync_lobby {0}".F(lobbyInfo.Serialize())), + Order.Command($"sync_lobby {lobbyInfo.Serialize()}"), Order.Command("startgame") }; @@ -439,7 +439,7 @@ namespace OpenRA throw new InvalidOperationException("Game.Mod argument missing."); if (!Mods.ContainsKey(mod)) - throw new InvalidOperationException("Unknown or invalid mod '{0}'.".F(mod)); + throw new InvalidOperationException($"Unknown or invalid mod '{mod}'."); Console.WriteLine("Loading mod: {0}", mod); @@ -988,8 +988,8 @@ namespace OpenRA { var orders = new List { - Order.Command("option gamespeed {0}".F("default")), - Order.Command("state {0}".F(Session.ClientState.Ready)) + Order.Command("option gamespeed default"), + Order.Command($"state {Session.ClientState.Ready}") }; var path = Platform.ResolvePath(launchMap); @@ -997,7 +997,7 @@ namespace OpenRA ModData.MapCache.SingleOrDefault(m => m.Package.Name == path); if (map == null) - throw new InvalidOperationException("Could not find map '{0}'.".F(launchMap)); + throw new InvalidOperationException($"Could not find map '{launchMap}'."); CreateAndStartLocalServer(map.Uid, orders); } diff --git a/OpenRA.Game/GameInformation.cs b/OpenRA.Game/GameInformation.cs index e78d1bdf6c..e00494ae04 100644 --- a/OpenRA.Game/GameInformation.cs +++ b/OpenRA.Game/GameInformation.cs @@ -76,7 +76,7 @@ namespace OpenRA } catch (YamlException) { - Log.Write("debug", "GameInformation deserialized invalid MiniYaml:\n{0}".F(data)); + Log.Write("debug", $"GameInformation deserialized invalid MiniYaml:\n{data}"); throw; } } @@ -89,7 +89,7 @@ namespace OpenRA }; for (var i = 0; i < Players.Count; i++) - nodes.Add(new MiniYamlNode("Player@{0}".F(i), FieldSaver.Save(Players[i]))); + nodes.Add(new MiniYamlNode($"Player@{i}", FieldSaver.Save(Players[i]))); return nodes.WriteToString(); } diff --git a/OpenRA.Game/GameRules/ActorInfo.cs b/OpenRA.Game/GameRules/ActorInfo.cs index 6d3856563f..fc0777d716 100644 --- a/OpenRA.Game/GameRules/ActorInfo.cs +++ b/OpenRA.Game/GameRules/ActorInfo.cs @@ -61,7 +61,7 @@ namespace OpenRA } catch (YamlException e) { - throw new YamlException("Actor type {0}: {1}".F(name, e.Message)); + throw new YamlException($"Actor type {name}: {e.Message}"); } } @@ -76,8 +76,7 @@ namespace OpenRA static TraitInfo LoadTraitInfo(ObjectCreator creator, string traitName, MiniYaml my) { if (!string.IsNullOrEmpty(my.Value)) - throw new YamlException("Junk value `{0}` on trait node {1}" - .F(my.Value, traitName)); + throw new YamlException($"Junk value `{my.Value}` on trait node {traitName}"); // HACK: The linter does not want to crash when a trait doesn't exist but only print an error instead // ObjectCreator will only return null to signal us to abort here if the linter is running diff --git a/OpenRA.Game/GameRules/Ruleset.cs b/OpenRA.Game/GameRules/Ruleset.cs index 235a4dc551..57b178bc0e 100644 --- a/OpenRA.Game/GameRules/Ruleset.cs +++ b/OpenRA.Game/GameRules/Ruleset.cs @@ -60,7 +60,7 @@ namespace OpenRA } catch (YamlException e) { - throw new YamlException("Actor type {0}: {1}".F(a.Name, e.Message)); + throw new YamlException($"Actor type {a.Name}: {e.Message}"); } } } @@ -75,7 +75,7 @@ namespace OpenRA } catch (YamlException e) { - throw new YamlException("Projectile type {0}: {1}".F(weapon.Key, e.Message)); + throw new YamlException($"Projectile type {weapon.Key}: {e.Message}"); } } @@ -89,7 +89,7 @@ namespace OpenRA } catch (YamlException e) { - throw new YamlException("Weapon type {0}: {1}".F(weapon.Key, e.Message)); + throw new YamlException($"Weapon type {weapon.Key}: {e.Message}"); } } } diff --git a/OpenRA.Game/GameSpeed.cs b/OpenRA.Game/GameSpeed.cs index 97ccc04630..e1880c7a82 100644 --- a/OpenRA.Game/GameSpeed.cs +++ b/OpenRA.Game/GameSpeed.cs @@ -50,7 +50,7 @@ namespace OpenRA catch (FieldLoader.MissingFieldsException e) { var label = e.Missing.Length > 1 ? "Required properties missing" : "Required property missing"; - throw new YamlException("Error parsing GameSpeed {0}: {1}: {2}".F(node.Key, label, e.Missing.JoinWith(", "))); + throw new YamlException($"Error parsing GameSpeed {node.Key}: {label}: {e.Missing.JoinWith(", ")}"); } } diff --git a/OpenRA.Game/Graphics/CursorManager.cs b/OpenRA.Game/Graphics/CursorManager.cs index 643872b141..02dec8bc55 100644 --- a/OpenRA.Game/Graphics/CursorManager.cs +++ b/OpenRA.Game/Graphics/CursorManager.cs @@ -231,7 +231,7 @@ namespace OpenRA.Graphics // All palettes must be explicitly referenced, even if they are embedded in the sprite. if (palette == null) - throw new InvalidOperationException("Cursor sequence `{0}` attempted to load an indexed sprite but does not define Palette".F(name)); + throw new InvalidOperationException($"Cursor sequence `{name}` attempted to load an indexed sprite but does not define Palette"); var width = frame.Size.Width; var height = frame.Size.Height; diff --git a/OpenRA.Game/Graphics/CursorProvider.cs b/OpenRA.Game/Graphics/CursorProvider.cs index 370dc09a68..583d46998a 100644 --- a/OpenRA.Game/Graphics/CursorProvider.cs +++ b/OpenRA.Game/Graphics/CursorProvider.cs @@ -59,7 +59,7 @@ namespace OpenRA.Graphics try { return Cursors[cursor]; } catch (KeyNotFoundException) { - throw new InvalidOperationException("Cursor does not have a sequence `{0}`".F(cursor)); + throw new InvalidOperationException($"Cursor does not have a sequence `{cursor}`"); } } } diff --git a/OpenRA.Game/Graphics/HardwarePalette.cs b/OpenRA.Game/Graphics/HardwarePalette.cs index 8d44440976..024902f09c 100644 --- a/OpenRA.Game/Graphics/HardwarePalette.cs +++ b/OpenRA.Game/Graphics/HardwarePalette.cs @@ -40,20 +40,20 @@ namespace OpenRA.Graphics return mutable.AsReadOnly(); if (palettes.TryGetValue(name, out var immutable)) return immutable; - throw new InvalidOperationException("Palette `{0}` does not exist".F(name)); + throw new InvalidOperationException($"Palette `{name}` does not exist"); } public int GetPaletteIndex(string name) { if (!indices.TryGetValue(name, out var ret)) - throw new InvalidOperationException("Palette `{0}` does not exist".F(name)); + throw new InvalidOperationException($"Palette `{name}` does not exist"); return ret; } public void AddPalette(string name, ImmutablePalette p, bool allowModifiers) { if (palettes.ContainsKey(name)) - throw new InvalidOperationException("Palette {0} has already been defined".F(name)); + throw new InvalidOperationException($"Palette {name} has already been defined"); int index = palettes.Count; indices.Add(name, index); @@ -78,7 +78,7 @@ namespace OpenRA.Graphics else if (palettes.ContainsKey(name)) CopyPaletteToBuffer(indices[name], palettes[name] = new ImmutablePalette(p)); else - throw new InvalidOperationException("Palette `{0}` does not exist".F(name)); + throw new InvalidOperationException($"Palette `{name}` does not exist"); CopyBufferToTexture(); } diff --git a/OpenRA.Game/Graphics/ModelRenderer.cs b/OpenRA.Game/Graphics/ModelRenderer.cs index 25db339089..259a604215 100644 --- a/OpenRA.Game/Graphics/ModelRenderer.cs +++ b/OpenRA.Game/Graphics/ModelRenderer.cs @@ -205,7 +205,7 @@ namespace OpenRA.Graphics var t = m.Model.TransformationMatrix(i, frame); var it = Util.MatrixInverse(t); if (it == null) - throw new InvalidOperationException("Failed to invert the transformed matrix of frame {0} during RenderAsync.".F(i)); + throw new InvalidOperationException($"Failed to invert the transformed matrix of frame {i} during RenderAsync."); // Transform light vector from shadow -> world -> limb coords var lightDirection = ExtractRotationVector(Util.MatrixMultiply(it, lightTransform)); diff --git a/OpenRA.Game/Graphics/SequenceProvider.cs b/OpenRA.Game/Graphics/SequenceProvider.cs index ce258ed8f0..51ef0356fa 100644 --- a/OpenRA.Game/Graphics/SequenceProvider.cs +++ b/OpenRA.Game/Graphics/SequenceProvider.cs @@ -72,10 +72,10 @@ namespace OpenRA.Graphics public ISpriteSequence GetSequence(string unitName, string sequenceName) { if (!sequences.Value.TryGetValue(unitName, out var unitSeq)) - throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName)); + throw new InvalidOperationException($"Unit `{unitName}` does not have any sequences defined."); if (!unitSeq.Value.TryGetValue(sequenceName, out var seq)) - throw new InvalidOperationException("Unit `{0}` does not have a sequence named `{1}`".F(unitName, sequenceName)); + throw new InvalidOperationException($"Unit `{unitName}` does not have a sequence named `{sequenceName}`"); return seq; } @@ -90,7 +90,7 @@ namespace OpenRA.Graphics public bool HasSequence(string unitName, string sequenceName) { if (!sequences.Value.TryGetValue(unitName, out var unitSeq)) - throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName)); + throw new InvalidOperationException($"Unit `{unitName}` does not have any sequences defined."); return unitSeq.Value.ContainsKey(sequenceName); } @@ -98,7 +98,7 @@ namespace OpenRA.Graphics public IEnumerable Sequences(string unitName) { if (!sequences.Value.TryGetValue(unitName, out var unitSeq)) - throw new InvalidOperationException("Unit `{0}` does not have any sequences defined.".F(unitName)); + throw new InvalidOperationException($"Unit `{unitName}` does not have any sequences defined."); return unitSeq.Value.Keys; } diff --git a/OpenRA.Game/Graphics/SheetBuilder.cs b/OpenRA.Game/Graphics/SheetBuilder.cs index 76e59fb98f..c824a6726c 100644 --- a/OpenRA.Game/Graphics/SheetBuilder.cs +++ b/OpenRA.Game/Graphics/SheetBuilder.cs @@ -61,7 +61,7 @@ namespace OpenRA.Graphics case SpriteFrameType.Rgba32: case SpriteFrameType.Rgb24: return SheetType.BGRA; - default: throw new NotImplementedException("Unknown SpriteFrameType {0}".F(t)); + default: throw new NotImplementedException($"Unknown SpriteFrameType {t}"); } } diff --git a/OpenRA.Game/Graphics/SpriteFont.cs b/OpenRA.Game/Graphics/SpriteFont.cs index 6a9136aa5f..74ddf29232 100644 --- a/OpenRA.Game/Graphics/SpriteFont.cs +++ b/OpenRA.Game/Graphics/SpriteFont.cs @@ -43,7 +43,7 @@ namespace OpenRA.Graphics // Pre-cache small font sizes so glyphs are immediately available when we need them if (size <= 24) - using (new PerfTimer("Precache {0} {1}px".F(name, size))) + using (new PerfTimer($"Precache {name} {size}px")) for (var n = (char)0x20; n < (char)0x7f; n++) if (glyphs[n] == null) throw new InvalidOperationException(); diff --git a/OpenRA.Game/Graphics/SpriteRenderer.cs b/OpenRA.Game/Graphics/SpriteRenderer.cs index 6416c70cee..60abb23ef9 100644 --- a/OpenRA.Game/Graphics/SpriteRenderer.cs +++ b/OpenRA.Game/Graphics/SpriteRenderer.cs @@ -19,7 +19,7 @@ namespace OpenRA.Graphics public class SpriteRenderer : Renderer.IBatchRenderer { public const int SheetCount = 7; - static readonly string[] SheetIndexToTextureName = Exts.MakeArray(SheetCount, i => "Texture{0}".F(i)); + static readonly string[] SheetIndexToTextureName = Exts.MakeArray(SheetCount, i => $"Texture{i}"); readonly Renderer renderer; readonly IShader shader; @@ -173,7 +173,7 @@ namespace OpenRA.Graphics // PERF: methods that throw won't be inlined by the JIT, so extract a static helper for use on hot paths static void ThrowSheetOverflow(string paramName) { - throw new ArgumentException("SpriteRenderer only supports {0} simultaneous textures".F(SheetCount), paramName); + throw new ArgumentException($"SpriteRenderer only supports {SheetCount} simultaneous textures", paramName); } // For RGBAColorRenderer diff --git a/OpenRA.Game/Graphics/Util.cs b/OpenRA.Game/Graphics/Util.cs index 29239854ec..50bc82bfce 100644 --- a/OpenRA.Game/Graphics/Util.cs +++ b/OpenRA.Game/Graphics/Util.cs @@ -108,7 +108,7 @@ namespace OpenRA.Graphics } default: - throw new InvalidOperationException("Unknown SpriteFrameType {0}".F(srcType)); + throw new InvalidOperationException($"Unknown SpriteFrameType {srcType}"); } var cc = Color.FromArgb(a, r, g, b); @@ -181,7 +181,7 @@ namespace OpenRA.Graphics // Pngs don't support BGR[A], so no need to include them here default: - throw new InvalidOperationException("Unknown SpriteFrameType {0}".F(src.Type)); + throw new InvalidOperationException($"Unknown SpriteFrameType {src.Type}"); } data[(y + j) * destStride + x + i] = PremultiplyAlpha(cc).ToArgb(); diff --git a/OpenRA.Game/Input/Hotkey.cs b/OpenRA.Game/Input/Hotkey.cs index 106a8883d6..a06bfe12f8 100644 --- a/OpenRA.Game/Input/Hotkey.cs +++ b/OpenRA.Game/Input/Hotkey.cs @@ -84,7 +84,7 @@ namespace OpenRA return obj is Hotkey o && (Hotkey?)o == this; } - public override string ToString() { return "{0} {1}".F(Key, Modifiers.ToString("F")); } + public override string ToString() { return $"{Key} {Modifiers.ToString("F")}"; } public string DisplayString() { diff --git a/OpenRA.Game/InstalledMods.cs b/OpenRA.Game/InstalledMods.cs index e157bb206a..bf6927829e 100644 --- a/OpenRA.Game/InstalledMods.cs +++ b/OpenRA.Game/InstalledMods.cs @@ -74,7 +74,7 @@ namespace OpenRA } catch (Exception e) { - Log.Write("debug", "Load mod '{0}': {1}".F(path, e)); + Log.Write("debug", $"Load mod '{path}': {e}"); } package?.Dispose(); diff --git a/OpenRA.Game/Manifest.cs b/OpenRA.Game/Manifest.cs index 7eb89b720f..23f0ffe57e 100644 --- a/OpenRA.Game/Manifest.cs +++ b/OpenRA.Game/Manifest.cs @@ -113,7 +113,7 @@ namespace OpenRA var filename = nodes[i].Value.Value; var contents = package.GetStream(filename); if (contents == null) - throw new YamlException("{0}: File `{1}` not found.".F(nodes[i].Location, filename)); + throw new YamlException($"{nodes[i].Location}: File `{filename}` not found."); nodes.RemoveAt(i); nodes.InsertRange(i, MiniYaml.FromStream(contents, filename)); @@ -182,7 +182,7 @@ namespace OpenRA var t = oc.FindType(kv.Key); if (t == null || !typeof(IGlobalModData).IsAssignableFrom(t)) - throw new InvalidDataException("`{0}` is not a valid mod manifest entry.".F(kv.Key)); + throw new InvalidDataException($"`{kv.Key}` is not a valid mod manifest entry."); IGlobalModData module; var ctor = t.GetConstructor(new[] { typeof(MiniYaml) }); diff --git a/OpenRA.Game/Map/ActorInitializer.cs b/OpenRA.Game/Map/ActorInitializer.cs index 4f0cf50691..61defd6d93 100644 --- a/OpenRA.Game/Map/ActorInitializer.cs +++ b/OpenRA.Game/Map/ActorInitializer.cs @@ -66,7 +66,7 @@ namespace OpenRA { var init = GetOrDefault(info); if (init == null) - throw new InvalidOperationException("TypeDictionary does not contain instance of type `{0}`".F(typeof(T))); + throw new InvalidOperationException($"TypeDictionary does not contain instance of type `{typeof(T)}`"); return init; } diff --git a/OpenRA.Game/Map/ActorReference.cs b/OpenRA.Game/Map/ActorReference.cs index 80e6afb1da..5b81f7f221 100644 --- a/OpenRA.Game/Map/ActorReference.cs +++ b/OpenRA.Game/Map/ActorReference.cs @@ -42,7 +42,7 @@ namespace OpenRA { var init = LoadInit(i.Key, i.Value); if (init is ISingleInstanceInit && dict.Contains(init.GetType())) - throw new InvalidDataException("Duplicate initializer '{0}'".F(init.GetType().Name)); + throw new InvalidDataException($"Duplicate initializer '{init.GetType().Name}'"); dict.Add(init); } @@ -68,7 +68,7 @@ namespace OpenRA var initInstance = initName.Split(ActorInfo.TraitInstanceSeparator); var type = Game.ModData.ObjectCreator.FindType(initInstance[0] + "Init"); if (type == null) - throw new InvalidDataException("Unknown initializer type '{0}Init'".F(initInstance[0])); + throw new InvalidDataException($"Unknown initializer type '{initInstance[0]}Init'"); var init = (ActorInit)FormatterServices.GetUninitializedObject(type); if (initInstance.Length > 1) @@ -76,7 +76,7 @@ namespace OpenRA var loader = type.GetMethod("Initialize", new[] { typeof(MiniYaml) }); if (loader == null) - throw new InvalidDataException("{0}Init does not define a yaml-assignable type.".F(initInstance[0])); + throw new InvalidDataException($"{initInstance[0]}Init does not define a yaml-assignable type."); loader.Invoke(init, new[] { initYaml }); return init; @@ -119,7 +119,7 @@ namespace OpenRA public void Add(ActorInit init) { if (init is ISingleInstanceInit && InitDict.Contains(init.GetType())) - throw new InvalidDataException("Duplicate initializer '{0}'".F(init.GetType().Name)); + throw new InvalidDataException($"Duplicate initializer '{init.GetType().Name}'"); InitDict.Add(init); } @@ -162,7 +162,7 @@ namespace OpenRA { var init = GetOrDefault(info); if (init == null) - throw new InvalidOperationException("TypeDictionary does not contain instance of type `{0}`".F(typeof(T))); + throw new InvalidOperationException($"TypeDictionary does not contain instance of type `{typeof(T)}`"); return init; } diff --git a/OpenRA.Game/Map/Map.cs b/OpenRA.Game/Map/Map.cs index baad403c54..4324b7885c 100644 --- a/OpenRA.Game/Map/Map.cs +++ b/OpenRA.Game/Map/Map.cs @@ -53,7 +53,7 @@ namespace OpenRA ResourcesOffset = s.ReadUInt32(); } else - throw new InvalidDataException("Unknown binary map format '{0}'".F(Format)); + throw new InvalidDataException($"Unknown binary map format '{Format}'"); } } @@ -100,7 +100,7 @@ namespace OpenRA if (node == null) { if (required) - throw new YamlException("Required field `{0}` not found in map.yaml".F(key)); + throw new YamlException($"Required field `{key}` not found in map.yaml"); return; } @@ -258,7 +258,7 @@ namespace OpenRA var contents = package.Contents.ToList(); foreach (var required in requiredFiles) if (!contents.Contains(required)) - throw new FileNotFoundException("Required file {0} not present in this map".F(required)); + throw new FileNotFoundException($"Required file {required} not present in this map"); var streams = new List(); try @@ -326,18 +326,18 @@ namespace OpenRA Package = package; if (!Package.Contains("map.yaml") || !Package.Contains("map.bin")) - throw new InvalidDataException("Not a valid map\n File: {0}".F(package.Name)); + throw new InvalidDataException($"Not a valid map\n File: {package.Name}"); var yaml = new MiniYaml(null, MiniYaml.FromStream(Package.GetStream("map.yaml"), package.Name)); foreach (var field in YamlFields) field.Deserialize(this, yaml.Nodes); if (MapFormat != SupportedMapFormat) - throw new InvalidDataException("Map format {0} is not supported.\n File: {1}".F(MapFormat, package.Name)); + throw new InvalidDataException($"Map format {MapFormat} is not supported.\n File: {package.Name}"); PlayerDefinitions = MiniYaml.NodesOrEmpty(yaml, "Players"); if (PlayerDefinitions.Count > 64) - throw new InvalidDataException("Maps must not define more than 64 players.\n File: {0}".F(package.Name)); + throw new InvalidDataException($"Maps must not define more than 64 players.\n File: {package.Name}"); ActorDefinitions = MiniYaml.NodesOrEmpty(yaml, "Actors"); @@ -1251,7 +1251,7 @@ namespace OpenRA if (maxRange >= Grid.TilesByDistance.Length) throw new ArgumentOutOfRangeException(nameof(maxRange), - "The requested range ({0}) cannot exceed the value of MaximumTileSearchRange ({1})".F(maxRange, Grid.MaximumTileSearchRange)); + $"The requested range ({maxRange}) cannot exceed the value of MaximumTileSearchRange ({Grid.MaximumTileSearchRange})"); for (var i = minRange; i <= maxRange; i++) { diff --git a/OpenRA.Game/Map/MapPlayers.cs b/OpenRA.Game/Map/MapPlayers.cs index 8a45a12978..092ce6d21f 100644 --- a/OpenRA.Game/Map/MapPlayers.cs +++ b/OpenRA.Game/Map/MapPlayers.cs @@ -50,7 +50,7 @@ namespace OpenRA Name = "Creeps", Faction = firstFaction, NonCombatant = true, - Enemies = Exts.MakeArray(playerCount, i => "Multi{0}".F(i)) + Enemies = Exts.MakeArray(playerCount, i => $"Multi{i}") } } }; @@ -59,7 +59,7 @@ namespace OpenRA { var p = new PlayerReference { - Name = "Multi{0}".F(index), + Name = $"Multi{index}", Faction = "Random", Playable = true, Enemies = new[] { "Creeps" } @@ -70,7 +70,7 @@ namespace OpenRA public List ToMiniYaml() { - return Players.Select(p => new MiniYamlNode("PlayerReference@{0}".F(p.Key), + return Players.Select(p => new MiniYamlNode($"PlayerReference@{p.Key}", FieldSaver.SaveDifferences(p.Value, new PlayerReference()))).ToList(); } } diff --git a/OpenRA.Game/Map/MapPreview.cs b/OpenRA.Game/Map/MapPreview.cs index 60ebccdf5f..4959b1c9bb 100644 --- a/OpenRA.Game/Map/MapPreview.cs +++ b/OpenRA.Game/Map/MapPreview.cs @@ -324,7 +324,7 @@ namespace OpenRA { var format = FieldLoader.GetValue("MapFormat", temp.Value); if (format != Map.SupportedMapFormat) - throw new InvalidDataException("Map format {0} is not supported.".F(format)); + throw new InvalidDataException($"Map format {format} is not supported."); } if (yaml.TryGetValue("Title", out temp)) diff --git a/OpenRA.Game/MiniYaml.cs b/OpenRA.Game/MiniYaml.cs index 81563c995b..3958f483e8 100644 --- a/OpenRA.Game/MiniYaml.cs +++ b/OpenRA.Game/MiniYaml.cs @@ -45,7 +45,7 @@ namespace OpenRA public struct SourceLocation { public string Filename; public int Line; - public override string ToString() { return "{0}:{1}".F(Filename, Line); } + public override string ToString() { return $"{Filename}:{Line}"; } } public SourceLocation Location; @@ -80,7 +80,7 @@ namespace OpenRA public override string ToString() { - return "{{YamlNode: {0} @ {1}}}".F(Key, Location); + return $"{{YamlNode: {Key} @ {Location}}}"; } public MiniYamlNode Clone() @@ -129,7 +129,7 @@ namespace OpenRA } catch (ArgumentException ex) { - throw new InvalidDataException("Duplicate key '{0}' in {1}".F(y.Key, y.Location), ex); + throw new InvalidDataException($"Duplicate key '{y.Key}' in {y.Location}", ex); } } @@ -205,7 +205,7 @@ namespace OpenRA } if (levels.Count <= level) - throw new YamlException("Bad indent in miniyaml at {0}".F(location)); + throw new YamlException($"Bad indent in miniyaml at {location}"); while (levels.Count > level + 1) levels.RemoveAt(levels.Count - 1); @@ -361,11 +361,10 @@ namespace OpenRA { if (!tree.TryGetValue(n.Value.Value, out var parent)) throw new YamlException( - "{0}: Parent type `{1}` not found".F(n.Location, n.Value.Value)); + $"{n.Location}: Parent type `{n.Value.Value}` not found"); if (inherited.ContainsKey(n.Value.Value)) - throw new YamlException("{0}: Parent type `{1}` was already inherited by this yaml tree at {2} (note: may be from a derived tree)" - .F(n.Location, n.Value.Value, inherited[n.Value.Value])); + throw new YamlException($"{n.Location}: Parent type `{n.Value.Value}` was already inherited by this yaml tree at {inherited[n.Value.Value]} (note: may be from a derived tree)"); inherited.Add(n.Value.Value, n.Location); foreach (var r in ResolveInherits(n.Key, parent, tree, inherited)) @@ -375,7 +374,7 @@ namespace OpenRA { var removed = n.Key.Substring(1); if (resolved.RemoveAll(r => r.Key == removed) == 0) - throw new YamlException("{0}: There are no elements with key `{1}` to remove".F(n.Location, removed)); + throw new YamlException($"{n.Location}: There are no elements with key `{removed}` to remove"); } else MergeIntoResolved(n, resolved, tree, inherited); @@ -443,8 +442,8 @@ namespace OpenRA var ret = new List(); - var existingDict = existingNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => "{0} (at {1})".F(x.Key, x.Location)); - var overrideDict = overrideNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => "{0} (at {1})".F(x.Key, x.Location)); + var existingDict = existingNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => $"{x.Key} (at {x.Location})"); + var overrideDict = overrideNodes.ToDictionaryWithConflictLog(x => x.Key, "MiniYaml.Merge", null, x => $"{x.Key} (at {x.Location})"); var allKeys = existingDict.Keys.Union(overrideDict.Keys); foreach (var key in allKeys) diff --git a/OpenRA.Game/ModData.cs b/OpenRA.Game/ModData.cs index 4449bb3acb..6d9eda158c 100644 --- a/OpenRA.Game/ModData.cs +++ b/OpenRA.Game/ModData.cs @@ -81,7 +81,7 @@ namespace OpenRA var terrainLoader = ObjectCreator.FindType(terrainFormat.Type + "Loader"); var terrainCtor = terrainLoader?.GetConstructor(new[] { typeof(ModData) }); if (terrainLoader == null || !terrainLoader.GetInterfaces().Contains(typeof(ITerrainLoader)) || terrainCtor == null) - throw new InvalidOperationException("Unable to find a terrain loader for type '{0}'.".F(terrainFormat.Type)); + throw new InvalidOperationException($"Unable to find a terrain loader for type '{terrainFormat.Type}'."); TerrainLoader = (ITerrainLoader)terrainCtor.Invoke(new[] { this }); @@ -89,7 +89,7 @@ namespace OpenRA var sequenceLoader = ObjectCreator.FindType(sequenceFormat.Type + "Loader"); var sequenceCtor = sequenceLoader != null ? sequenceLoader.GetConstructor(new[] { typeof(ModData) }) : null; if (sequenceLoader == null || !sequenceLoader.GetInterfaces().Contains(typeof(ISpriteSequenceLoader)) || sequenceCtor == null) - throw new InvalidOperationException("Unable to find a sequence loader for type '{0}'.".F(sequenceFormat.Type)); + throw new InvalidOperationException($"Unable to find a sequence loader for type '{sequenceFormat.Type}'."); SpriteSequenceLoader = (ISpriteSequenceLoader)sequenceCtor.Invoke(new[] { this }); @@ -97,7 +97,7 @@ namespace OpenRA var modelLoader = ObjectCreator.FindType(modelFormat.Type + "Loader"); var modelCtor = modelLoader != null ? modelLoader.GetConstructor(new[] { typeof(ModData) }) : null; if (modelLoader == null || !modelLoader.GetInterfaces().Contains(typeof(IModelSequenceLoader)) || modelCtor == null) - throw new InvalidOperationException("Unable to find a model loader for type '{0}'.".F(modelFormat.Type)); + throw new InvalidOperationException($"Unable to find a model loader for type '{modelFormat.Type}'."); ModelSequenceLoader = (IModelSequenceLoader)modelCtor.Invoke(new[] { this }); ModelSequenceLoader.OnMissingModelError = s => Log.Write("debug", s); @@ -156,7 +156,7 @@ namespace OpenRA LoadScreen?.Display(); if (MapCache[uid].Status != MapStatus.Available) - throw new InvalidDataException("Invalid map uid: {0}".F(uid)); + throw new InvalidDataException($"Invalid map uid: {uid}"); Map map; using (new Support.PerfTimer("Map")) diff --git a/OpenRA.Game/Network/Connection.cs b/OpenRA.Game/Network/Connection.cs index 9525ecf7ac..d67535411b 100644 --- a/OpenRA.Game/Network/Connection.cs +++ b/OpenRA.Game/Network/Connection.cs @@ -156,7 +156,7 @@ namespace OpenRA.Network this.target = target; new Thread(NetworkConnectionConnect) { - Name = "{0} (connect to {1})".F(GetType().Name, target), + Name = $"{GetType().Name} (connect to {target})", IsBackground = true }.Start(); } @@ -189,11 +189,11 @@ namespace OpenRA.Network catch (Exception ex) { errorMessage = "Failed to connect"; - Log.Write("client", "Failed to connect to {0}: {1}".F(endpoint, ex.Message)); + Log.Write("client", $"Failed to connect to {endpoint}: {ex.Message}"); } }) { - Name = "{0} (connect to {1})".F(GetType().Name, endpoint), + Name = $"{GetType().Name} (connect to {endpoint})", IsBackground = true }.Start(); } @@ -212,7 +212,7 @@ namespace OpenRA.Network new Thread(NetworkConnectionReceive) { - Name = "{0} (receive from {1})".F(GetType().Name, tcp.Client.RemoteEndPoint), + Name = $"{GetType().Name} (receive from {tcp.Client.RemoteEndPoint})", IsBackground = true }.Start(); } @@ -235,9 +235,7 @@ namespace OpenRA.Network var handshakeProtocol = reader.ReadInt32(); if (handshakeProtocol != ProtocolVersion.Handshake) - throw new InvalidOperationException( - "Handshake protocol version mismatch. Server={0} Client={1}" - .F(handshakeProtocol, ProtocolVersion.Handshake)); + throw new InvalidOperationException($"Handshake protocol version mismatch. Server={handshakeProtocol} Client={ProtocolVersion.Handshake}"); clientId = reader.ReadInt32(); connectionState = ConnectionState.Connected; @@ -255,7 +253,7 @@ namespace OpenRA.Network catch (Exception ex) { errorMessage = "Connection failed"; - Log.Write("client", "Connection to {0} failed: {1}".F(endpoint, ex.Message)); + Log.Write("client", $"Connection to {endpoint} failed: {ex.Message}"); } finally { diff --git a/OpenRA.Game/Network/ConnectionTarget.cs b/OpenRA.Game/Network/ConnectionTarget.cs index 0f502d895c..578f5333ff 100644 --- a/OpenRA.Game/Network/ConnectionTarget.cs +++ b/OpenRA.Game/Network/ConnectionTarget.cs @@ -56,7 +56,7 @@ namespace OpenRA.Network public override string ToString() { return endpoints - .Select(e => "{0}:{1}".F(e.Host, e.Port)) + .Select(e => $"{e.Host}:{e.Port}") .JoinWith("/"); } } diff --git a/OpenRA.Game/Network/FrameData.cs b/OpenRA.Game/Network/FrameData.cs index 991eb50072..d540ab78fe 100644 --- a/OpenRA.Game/Network/FrameData.cs +++ b/OpenRA.Game/Network/FrameData.cs @@ -23,7 +23,7 @@ namespace OpenRA.Network public override string ToString() { - return "ClientId: {0} {1}".F(Client, Order); + return $"ClientId: {Client} {Order}"; } } diff --git a/OpenRA.Game/Network/GameSave.cs b/OpenRA.Game/Network/GameSave.cs index 813f5be71d..9ddde104c8 100644 --- a/OpenRA.Game/Network/GameSave.cs +++ b/OpenRA.Game/Network/GameSave.cs @@ -71,7 +71,7 @@ namespace OpenRA.Network public MiniYamlNode Serialize(string key) { - return new MiniYamlNode("SlotClient@{0}".F(key), FieldSaver.Save(this)); + return new MiniYamlNode($"SlotClient@{key}", FieldSaver.Save(this)); } } @@ -195,7 +195,7 @@ namespace OpenRA.Network { if (data.Length != Order.SyncHashOrderLength) { - Log.Write("debug", "Dropped sync order with length {0}. Expected length {1}.".F(data.Length, Order.SyncHashOrderLength)); + Log.Write("debug", $"Dropped sync order with length {data.Length}. Expected length {Order.SyncHashOrderLength}."); return; } diff --git a/OpenRA.Game/Network/GameServer.cs b/OpenRA.Game/Network/GameServer.cs index c95d2a3dce..24b38dc0f4 100644 --- a/OpenRA.Game/Network/GameServer.cs +++ b/OpenRA.Game/Network/GameServer.cs @@ -135,7 +135,7 @@ namespace OpenRA.Network /// The list of spawnpoints that are disabled for this game public readonly int[] DisabledSpawnPoints = { }; - public string ModLabel => "{0} ({1})".F(ModTitle, Version); + public string ModLabel => $"{ModTitle} ({Version})"; static object LoadClients(MiniYaml yaml) { @@ -200,9 +200,9 @@ namespace OpenRA.Network .FirstOrDefault(m => m.Id == Mod); if (guessMod != null) - ModTitle = "{0}".F(guessMod.Title); + ModTitle = guessMod.Title; else - ModTitle = "Unknown mod: {0}".F(Mod); + ModTitle = $"Unknown mod: {Mod}"; } } diff --git a/OpenRA.Game/Network/Order.cs b/OpenRA.Game/Network/Order.cs index 954a446d2e..b9627223d7 100644 --- a/OpenRA.Game/Network/Order.cs +++ b/OpenRA.Game/Network/Order.cs @@ -405,7 +405,7 @@ namespace OpenRA } default: - throw new InvalidDataException("Cannot serialize order type {0}".F(Type)); + throw new InvalidDataException($"Cannot serialize order type {Type}"); } return ret.ToArray(); @@ -413,10 +413,8 @@ namespace OpenRA public override string ToString() { - return ("OrderString: \"{0}\" \n\t Type: \"{1}\". \n\t Subject: \"{2}\". \n\t Target: \"{3}\"." + - "\n\t TargetString: \"{4}\".\n\t IsImmediate: {5}.\n\t Player(PlayerName): {6}\n").F( - OrderString, Type, Subject, Target, TargetString, IsImmediate, - Player != null ? Player.PlayerName : null); + return $"OrderString: \"{OrderString}\" \n\t Type: \"{Type}\". \n\t Subject: \"{Subject}\". \n\t Target: \"{Target}\"." + + $"\n\t TargetString: \"{TargetString}\".\n\t IsImmediate: {IsImmediate}.\n\t Player(PlayerName): {Player?.PlayerName}\n"; } } } diff --git a/OpenRA.Game/Network/OrderManager.cs b/OpenRA.Game/Network/OrderManager.cs index 91282941b4..78a858bf49 100644 --- a/OpenRA.Game/Network/OrderManager.cs +++ b/OpenRA.Game/Network/OrderManager.cs @@ -60,7 +60,7 @@ namespace OpenRA.Network void OutOfSync(int frame) { syncReport.DumpSyncReport(frame, frameData.OrdersForFrame(World, frame)); - throw new InvalidOperationException("Out of sync in frame {0}.\n Compare syncreport.log with other players.".F(frame)); + throw new InvalidOperationException($"Out of sync in frame {frame}.\n Compare syncreport.log with other players."); } public void StartGame() @@ -126,7 +126,7 @@ namespace OpenRA.Network { if (packet.Length != 4 + Order.SyncHashOrderLength) { - Log.Write("debug", "Dropped sync order with length {0}. Expected length {1}.".F(packet.Length, 4 + Order.SyncHashOrderLength)); + Log.Write("debug", $"Dropped sync order with length {packet.Length}. Expected length {4 + Order.SyncHashOrderLength}."); return; } diff --git a/OpenRA.Game/Network/ReplayRecorder.cs b/OpenRA.Game/Network/ReplayRecorder.cs index 63f87f9732..7a58fe9536 100644 --- a/OpenRA.Game/Network/ReplayRecorder.cs +++ b/OpenRA.Game/Network/ReplayRecorder.cs @@ -56,7 +56,7 @@ namespace OpenRA.Network var id = -1; while (file == null) { - var fullFilename = Path.Combine(dir, id < 0 ? "{0}.orarep".F(filename) : "{0}-{1}.orarep".F(filename, id)); + var fullFilename = Path.Combine(dir, id < 0 ? $"{filename}.orarep" : $"{filename}-{id}.orarep"); id++; try { @@ -65,8 +65,7 @@ namespace OpenRA.Network catch (IOException ex) { if (id > CreateReplayFileMaxRetryCount) - throw new ArgumentException( - "Error creating replay file \"{0}.orarep\"".F(filename), ex); + throw new ArgumentException($"Error creating replay file \"{filename}.orarep\"", ex); } } diff --git a/OpenRA.Game/Network/Session.cs b/OpenRA.Game/Network/Session.cs index 3ec4484357..da1bf26e2b 100644 --- a/OpenRA.Game/Network/Session.cs +++ b/OpenRA.Game/Network/Session.cs @@ -37,7 +37,7 @@ namespace OpenRA.Network { // Follow convention used by Google Analytics: remove last octet var b = ip.GetAddressBytes(); - return "{0}.{1}.{2}.*".F(b[0], b[1], b[2]); + return $"{b[0]}.{b[1]}.{b[2]}.*"; } return null; @@ -82,11 +82,11 @@ namespace OpenRA.Network } catch (YamlException) { - throw new YamlException("Session deserialized invalid MiniYaml:\n{0}".F(data)); + throw new YamlException($"Session deserialized invalid MiniYaml:\n{data}"); } catch (InvalidOperationException) { - throw new YamlException("Session deserialized invalid MiniYaml:\n{0}".F(data)); + throw new YamlException($"Session deserialized invalid MiniYaml:\n{data}"); } } @@ -159,7 +159,7 @@ namespace OpenRA.Network public MiniYamlNode Serialize() { - return new MiniYamlNode("Client@{0}".F(Index), FieldSaver.Save(this)); + return new MiniYamlNode($"Client@{Index}", FieldSaver.Save(this)); } } @@ -182,7 +182,7 @@ namespace OpenRA.Network public MiniYamlNode Serialize() { - return new MiniYamlNode("ClientPing@{0}".F(Index), FieldSaver.Save(this)); + return new MiniYamlNode($"ClientPing@{Index}", FieldSaver.Save(this)); } } @@ -206,7 +206,7 @@ namespace OpenRA.Network public MiniYamlNode Serialize() { - return new MiniYamlNode("Slot@{0}".F(PlayerReference), FieldSaver.Save(this)); + return new MiniYamlNode($"Slot@{PlayerReference}", FieldSaver.Save(this)); } } diff --git a/OpenRA.Game/Network/SyncReport.cs b/OpenRA.Game/Network/SyncReport.cs index dbf6810801..2f435b0da5 100644 --- a/OpenRA.Game/Network/SyncReport.cs +++ b/OpenRA.Game/Network/SyncReport.cs @@ -117,12 +117,12 @@ namespace OpenRA.Network Log.Write("sync", "Synced Traits:"); foreach (var a in r.Traits) { - Log.Write("sync", "\t {0} {1} {2} {3} ({4})".F(a.ActorID, a.Type, a.Owner, a.Trait, a.Hash)); + Log.Write("sync", $"\t {a.ActorID} {a.Type} {a.Owner} {a.Trait} ({a.Hash})"); var nvp = a.NamesValues; for (int i = 0; i < nvp.Names.Length; i++) if (nvp.Values[i] != null) - Log.Write("sync", "\t\t {0}: {1}".F(nvp.Names[i], nvp.Values[i])); + Log.Write("sync", $"\t\t {nvp.Names[i]}: {nvp.Values[i]}"); } Log.Write("sync", "Synced Effects:"); @@ -133,7 +133,7 @@ namespace OpenRA.Network var nvp = e.NamesValues; for (int i = 0; i < nvp.Names.Length; i++) if (nvp.Values[i] != null) - Log.Write("sync", "\t\t {0}: {1}".F(nvp.Names[i], nvp.Values[i])); + Log.Write("sync", $"\t\t {nvp.Names[i]}: {nvp.Values[i]}"); } Log.Write("sync", "Orders Issued:"); diff --git a/OpenRA.Game/Network/UnitOrders.cs b/OpenRA.Game/Network/UnitOrders.cs index 3a303f5925..6345721f43 100644 --- a/OpenRA.Game/Network/UnitOrders.cs +++ b/OpenRA.Game/Network/UnitOrders.cs @@ -170,7 +170,7 @@ namespace OpenRA.Network if (orderManager.World.Paused != pause && world != null && world.LobbyInfo.NonBotClients.Count() > 1) { - var pausetext = "The game is {0} by {1}".F(pause ? "paused" : "un-paused", client.Name); + var pausetext = $"The game is {(pause ? "paused" : "un-paused")} by {client.Name}"; Game.AddSystemLine(pausetext); } diff --git a/OpenRA.Game/ObjectCreator.cs b/OpenRA.Game/ObjectCreator.cs index 75f67d2189..ca3d34b208 100644 --- a/OpenRA.Game/ObjectCreator.cs +++ b/OpenRA.Game/ObjectCreator.cs @@ -41,7 +41,7 @@ namespace OpenRA { var resolvedPath = FileSystem.FileSystem.ResolveAssemblyPath(path, manifest, mods); if (resolvedPath == null) - throw new FileNotFoundException("Assembly `{0}` not found.".F(path)); + throw new FileNotFoundException($"Assembly `{path}` not found."); LoadAssembly(assemblyList, resolvedPath); } @@ -111,7 +111,7 @@ namespace OpenRA if (MissingTypeAction != null) MissingTypeAction(className); else - throw new InvalidOperationException("Cannot locate type: {0}".F(className)); + throw new InvalidOperationException($"Cannot locate type: {className}"); return default(T); } @@ -151,7 +151,7 @@ namespace OpenRA for (var i = 0; i < p.Length; i++) { var key = p[i].Name; - if (!args.ContainsKey(key)) throw new InvalidOperationException("ObjectCreator: key `{0}' not found".F(key)); + if (!args.ContainsKey(key)) throw new InvalidOperationException($"ObjectCreator: key `{key}' not found"); a[i] = args[key]; } @@ -177,7 +177,7 @@ namespace OpenRA { var loader = FindType(format + "Loader"); if (loader == null || !loader.GetInterfaces().Contains(typeof(TLoader))) - throw new InvalidOperationException("Unable to find a {0} loader for type '{1}'.".F(name, format)); + throw new InvalidOperationException($"Unable to find a {name} loader for type '{format}'."); loaders.Add((TLoader)CreateBasic(loader)); } diff --git a/OpenRA.Game/Platform.cs b/OpenRA.Game/Platform.cs index e89a707a85..313bbe8bb7 100644 --- a/OpenRA.Game/Platform.cs +++ b/OpenRA.Game/Platform.cs @@ -64,13 +64,13 @@ namespace OpenRA { var mono = Type.GetType("Mono.Runtime"); if (mono == null) - return ".NET CLR {0}".F(Environment.Version); + return $".NET CLR {Environment.Version}"; var version = mono.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (version == null) - return "Mono (unknown version) CLR {0}".F(Environment.Version); + return $"Mono (unknown version) CLR {Environment.Version}"; - return "Mono {0} CLR {1}".F(version.Invoke(null, null), Environment.Version); + return $"Mono {version.Invoke(null, null)} CLR {Environment.Version}"; } } diff --git a/OpenRA.Game/Player.cs b/OpenRA.Game/Player.cs index a9c0f65a12..5d05338a39 100644 --- a/OpenRA.Game/Player.cs +++ b/OpenRA.Game/Player.cs @@ -118,7 +118,7 @@ namespace OpenRA selected = selectableFactions.FirstOrDefault(f => f.InternalName == faction); if (selected == null) - throw new YamlException("Unknown faction: {0}".F(faction)); + throw new YamlException($"Unknown faction: {faction}"); } return selected; @@ -143,7 +143,7 @@ namespace OpenRA { var botInfo = botInfos.First(b => b.Type == client.Bot); var botsOfSameType = clients.Where(c => c.Bot == client.Bot).ToArray(); - return botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1); + return botsOfSameType.Length == 1 ? botInfo.Name : $"{botInfo.Name} {botsOfSameType.IndexOf(client) + 1}"; } return client.Name; @@ -230,7 +230,7 @@ namespace OpenRA public override string ToString() { - return "{0} ({1})".F(PlayerName, ClientIndex); + return $"{PlayerName} ({ClientIndex})"; } public PlayerRelationship RelationshipWith(Player other) @@ -305,7 +305,7 @@ namespace OpenRA public LuaValue ToString(LuaRuntime runtime) { - return "Player ({0})".F(PlayerName); + return $"Player ({PlayerName})"; } #endregion diff --git a/OpenRA.Game/Primitives/Rectangle.cs b/OpenRA.Game/Primitives/Rectangle.cs index f5166d526a..6c9cc8e9c3 100644 --- a/OpenRA.Game/Primitives/Rectangle.cs +++ b/OpenRA.Game/Primitives/Rectangle.cs @@ -126,7 +126,7 @@ namespace OpenRA.Primitives public override string ToString() { - return "{0},{1},{2},{3}".F(X, Y, Width, Height); + return $"{X},{Y},{Width},{Height}"; } } } diff --git a/OpenRA.Game/Primitives/Size.cs b/OpenRA.Game/Primitives/Size.cs index 36f1e3a7d4..4c4fd72466 100644 --- a/OpenRA.Game/Primitives/Size.cs +++ b/OpenRA.Game/Primitives/Size.cs @@ -66,7 +66,7 @@ namespace OpenRA.Primitives public override string ToString() { - return string.Format("{{Width={0}, Height={1}}}", Width, Height); + return $"{{Width={Width}, Height={Height}}}"; } } } diff --git a/OpenRA.Game/Primitives/SpatiallyPartitioned.cs b/OpenRA.Game/Primitives/SpatiallyPartitioned.cs index 5b9e9172eb..e5e4132b2b 100644 --- a/OpenRA.Game/Primitives/SpatiallyPartitioned.cs +++ b/OpenRA.Game/Primitives/SpatiallyPartitioned.cs @@ -33,7 +33,7 @@ namespace OpenRA.Primitives void ValidateBounds(T actor, Rectangle bounds) { if (bounds.Width == 0 || bounds.Height == 0) - throw new ArgumentException("Bounds of actor {0} are empty.".F(actor), nameof(bounds)); + throw new ArgumentException($"Bounds of actor {actor} are empty.", nameof(bounds)); } public void Add(T item, Rectangle bounds) diff --git a/OpenRA.Game/Primitives/TypeDictionary.cs b/OpenRA.Game/Primitives/TypeDictionary.cs index f4e960224b..129f1d5620 100644 --- a/OpenRA.Game/Primitives/TypeDictionary.cs +++ b/OpenRA.Game/Primitives/TypeDictionary.cs @@ -64,12 +64,12 @@ namespace OpenRA.Primitives if (!data.TryGetValue(t, out var ret)) { if (throwsIfMissing) - throw new InvalidOperationException("TypeDictionary does not contain instance of type `{0}`".F(t)); + throw new InvalidOperationException($"TypeDictionary does not contain instance of type `{t}`"); return null; } if (ret.Count > 1) - throw new InvalidOperationException("TypeDictionary contains multiple instances of type `{0}`".F(t)); + throw new InvalidOperationException($"TypeDictionary contains multiple instances of type `{t}`"); return ret[0]; } diff --git a/OpenRA.Game/Primitives/float3.cs b/OpenRA.Game/Primitives/float3.cs index 94253dc8f2..57dc76882c 100644 --- a/OpenRA.Game/Primitives/float3.cs +++ b/OpenRA.Game/Primitives/float3.cs @@ -58,7 +58,7 @@ namespace OpenRA return obj is float3 o && (float3?)o == this; } - public override string ToString() { return "{0},{1},{2}".F(X, Y, Z); } + public override string ToString() { return $"{X},{Y},{Z}"; } public static readonly float3 Zero = new float3(0, 0, 0); public static readonly float3 Ones = new float3(1, 1, 1); diff --git a/OpenRA.Game/Renderer.cs b/OpenRA.Game/Renderer.cs index 290db21739..bed41b3ca2 100644 --- a/OpenRA.Game/Renderer.cs +++ b/OpenRA.Game/Renderer.cs @@ -181,7 +181,7 @@ namespace OpenRA public void BeginWorld(Rectangle worldViewport) { if (renderType != RenderType.None) - throw new InvalidOperationException("BeginWorld called with renderType = {0}, expected RenderType.None.".F(renderType)); + throw new InvalidOperationException($"BeginWorld called with renderType = {renderType}, expected RenderType.None."); BeginFrame(); @@ -263,7 +263,7 @@ namespace OpenRA public void EndFrame(IInputHandler inputHandler) { if (renderType != RenderType.UI) - throw new InvalidOperationException("EndFrame called with renderType = {0}, expected RenderType.UI.".F(renderType)); + throw new InvalidOperationException($"EndFrame called with renderType = {renderType}, expected RenderType.UI."); Flush(); @@ -391,7 +391,7 @@ namespace OpenRA public void EnableAntialiasingFilter() { if (renderType != RenderType.UI) - throw new InvalidOperationException("EndFrame called with renderType = {0}, expected RenderType.UI.".F(renderType)); + throw new InvalidOperationException($"EndFrame called with renderType = {renderType}, expected RenderType.UI."); Flush(); SpriteRenderer.SetAntialiasingPixelsPerTexel(Window.EffectiveWindowScale); @@ -400,7 +400,7 @@ namespace OpenRA public void DisableAntialiasingFilter() { if (renderType != RenderType.UI) - throw new InvalidOperationException("EndFrame called with renderType = {0}, expected RenderType.UI.".F(renderType)); + throw new InvalidOperationException($"EndFrame called with renderType = {renderType}, expected RenderType.UI."); Flush(); SpriteRenderer.SetAntialiasingPixelsPerTexel(0); diff --git a/OpenRA.Game/Scripting/ScriptActorInterface.cs b/OpenRA.Game/Scripting/ScriptActorInterface.cs index 98a5661fb9..1acad16ba5 100644 --- a/OpenRA.Game/Scripting/ScriptActorInterface.cs +++ b/OpenRA.Game/Scripting/ScriptActorInterface.cs @@ -18,14 +18,14 @@ namespace OpenRA.Scripting { readonly Actor actor; - protected override string DuplicateKeyError(string memberName) { return "Actor '{0}' defines the command '{1}' on multiple traits".F(actor.Info.Name, memberName); } + protected override string DuplicateKeyError(string memberName) { return $"Actor '{actor.Info.Name}' defines the command '{memberName}' on multiple traits"; } protected override string MemberNotFoundError(string memberName) { var actorName = actor.Info.Name; if (actor.IsDead) actorName += " (dead)"; - return "Actor '{0}' does not define a property '{1}'".F(actorName, memberName); + return $"Actor '{actorName}' does not define a property '{memberName}'"; } public ScriptActorInterface(ScriptContext context, Actor actor) diff --git a/OpenRA.Game/Scripting/ScriptContext.cs b/OpenRA.Game/Scripting/ScriptContext.cs index d2bddcee1b..bd9f60ac7e 100644 --- a/OpenRA.Game/Scripting/ScriptContext.cs +++ b/OpenRA.Game/Scripting/ScriptContext.cs @@ -81,8 +81,8 @@ namespace OpenRA.Scripting /// public abstract class ScriptGlobal : ScriptObjectWrapper { - protected override string DuplicateKeyError(string memberName) { return "Table '{0}' defines multiple members '{1}'".F(Name, memberName); } - protected override string MemberNotFoundError(string memberName) { return "Table '{0}' does not define a property '{1}'".F(Name, memberName); } + protected override string DuplicateKeyError(string memberName) { return $"Table '{Name}' defines multiple members '{memberName}'"; } + protected override string MemberNotFoundError(string memberName) { return $"Table '{Name}' does not define a property '{memberName}'"; } public readonly string Name; public ScriptGlobal(ScriptContext context) @@ -92,7 +92,7 @@ namespace OpenRA.Scripting var type = GetType(); var names = type.GetCustomAttributes(true); if (names.Length != 1) - throw new InvalidOperationException("[ScriptGlobal] attribute not found for global table '{0}'".F(type)); + throw new InvalidOperationException($"[ScriptGlobal] attribute not found for global table '{type}'"); Name = names.First().Name; Bind(new[] { this }); @@ -187,7 +187,7 @@ namespace OpenRA.Scripting }); if (ctor == null) - throw new InvalidOperationException("{0} must define a constructor that takes a ScriptContext context parameter".F(b.Name)); + throw new InvalidOperationException($"{b.Name} must define a constructor that takes a ScriptContext context parameter"); var binding = (ScriptGlobal)ctor.Invoke(new[] { this }); using (var obj = binding.ToLuaValue(this)) @@ -236,7 +236,7 @@ namespace OpenRA.Scripting using (var registerGlobal = (LuaFunction)runtime.Globals["RegisterSandboxedGlobal"]) { if (runtime.Globals.ContainsKey(name)) - throw new LuaException("The global name '{0}' is reserved, and may not be used by a map actor".F(name)); + throw new LuaException($"The global name '{name}' is reserved, and may not be used by a map actor"); using (var obj = a.ToLuaValue(this)) registerGlobal.Call(name, obj).Dispose(); diff --git a/OpenRA.Game/Scripting/ScriptMemberExts.cs b/OpenRA.Game/Scripting/ScriptMemberExts.cs index 9db5a55d7e..b7174a6dc6 100644 --- a/OpenRA.Game/Scripting/ScriptMemberExts.cs +++ b/OpenRA.Game/Scripting/ScriptMemberExts.cs @@ -32,16 +32,16 @@ namespace OpenRA.Scripting ret = t.Name; if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) - ret = "{0}?".F(t.GetGenericArguments().Select(p => p.Name).First()); + ret = $"{t.GetGenericArguments().Select(p => p.Name).First()}?"; return ret; } public static string LuaDocString(this ParameterInfo pi) { - var ret = "{0} {1}".F(pi.ParameterType.LuaDocString(), pi.Name); + var ret = $"{pi.ParameterType.LuaDocString()} {pi.Name}"; if (pi.IsOptional) - ret += " = {0}".F(pi.DefaultValue != null ? pi.DefaultValue : "nil"); + ret += $" = {pi.DefaultValue ?? "nil"}"; return ret; } @@ -52,7 +52,7 @@ namespace OpenRA.Scripting if (methodInfo != null) { var parameters = methodInfo.GetParameters().Select(pi => pi.LuaDocString()); - return "{0} {1}({2})".F(methodInfo.ReturnType.LuaDocString(), mi.Name, parameters.JoinWith(", ")); + return $"{methodInfo.ReturnType.LuaDocString()} {mi.Name}({parameters.JoinWith(", ")})"; } var propertyInfo = mi as PropertyInfo; @@ -64,10 +64,10 @@ namespace OpenRA.Scripting if (propertyInfo.GetSetMethod() != null) types.Add("set;"); - return "{0} {1} {{ {2} }}".F(propertyInfo.PropertyType.LuaDocString(), mi.Name, types.JoinWith(" ")); + return $"{propertyInfo.PropertyType.LuaDocString()} {mi.Name} {{ {types.JoinWith(" ")} }}"; } - return "Unknown field: {0}".F(mi.Name); + return $"Unknown field: {mi.Name}"; } } } diff --git a/OpenRA.Game/Scripting/ScriptMemberWrapper.cs b/OpenRA.Game/Scripting/ScriptMemberWrapper.cs index 5521935811..101d2ddaa5 100644 --- a/OpenRA.Game/Scripting/ScriptMemberWrapper.cs +++ b/OpenRA.Game/Scripting/ScriptMemberWrapper.cs @@ -62,14 +62,14 @@ namespace OpenRA.Scripting if (i >= argCount) { if (!pi[i].IsOptional) - throw new LuaException("Argument '{0}' of '{1}' is not optional.".F(pi[i].LuaDocString(), Member.LuaDocString())); + throw new LuaException($"Argument '{pi[i].LuaDocString()}' of '{Member.LuaDocString()}' is not optional."); clrArgs[i] = pi[i].DefaultValue; continue; } if (!args[i].TryGetClrValue(pi[i].ParameterType, out clrArgs[i])) - throw new LuaException("Unable to convert parameter {0} to {1}".F(i, pi[i].ParameterType.Name)); + throw new LuaException($"Unable to convert parameter {i} to {pi[i].ParameterType.Name}"); } return mi.Invoke(Target, clrArgs).ToLuaValue(context); @@ -105,7 +105,7 @@ namespace OpenRA.Scripting if (IsGetProperty) return ((PropertyInfo)Member).GetValue(Target, null).ToLuaValue(context); - throw new LuaException("The property '{0}' is write-only".F(Member.Name)); + throw new LuaException($"The property '{Member.Name}' is write-only"); } public void Set(LuaRuntime runtime, LuaValue value) @@ -114,12 +114,12 @@ namespace OpenRA.Scripting { var pi = (PropertyInfo)Member; if (!value.TryGetClrValue(pi.PropertyType, out var clrValue)) - throw new LuaException("Unable to convert '{0}' to Clr type '{1}'".F(value.WrappedClrType().Name, pi.PropertyType)); + throw new LuaException($"Unable to convert '{value.WrappedClrType().Name}' to Clr type '{pi.PropertyType}'"); pi.SetValue(Target, clrValue, null); } else - throw new LuaException("The property '{0}' is read-only".F(Member.Name)); + throw new LuaException($"The property '{Member.Name}' is read-only"); } public static IEnumerable WrappableMembers(Type t) diff --git a/OpenRA.Game/Scripting/ScriptPlayerInterface.cs b/OpenRA.Game/Scripting/ScriptPlayerInterface.cs index 94e5960eb8..d96deb5240 100644 --- a/OpenRA.Game/Scripting/ScriptPlayerInterface.cs +++ b/OpenRA.Game/Scripting/ScriptPlayerInterface.cs @@ -18,8 +18,8 @@ namespace OpenRA.Scripting { readonly Player player; - protected override string DuplicateKeyError(string memberName) { return "Player '{0}' defines the command '{1}' on multiple traits".F(player.PlayerName, memberName); } - protected override string MemberNotFoundError(string memberName) { return "Player '{0}' does not define a property '{1}'".F(player.PlayerName, memberName); } + protected override string DuplicateKeyError(string memberName) { return $"Player '{player.PlayerName}' defines the command '{memberName}' on multiple traits"; } + protected override string MemberNotFoundError(string memberName) { return $"Player '{player.PlayerName}' does not define a property '{memberName}'"; } public ScriptPlayerInterface(ScriptContext context, Player player) : base(context) diff --git a/OpenRA.Game/Scripting/ScriptTypes.cs b/OpenRA.Game/Scripting/ScriptTypes.cs index b11b6aca1c..12a06fc8ba 100644 --- a/OpenRA.Game/Scripting/ScriptTypes.cs +++ b/OpenRA.Game/Scripting/ScriptTypes.cs @@ -126,7 +126,7 @@ namespace OpenRA.Scripting if (!elementHasClrValue || !(element is LuaValue)) kv.Value.Dispose(); if (!elementHasClrValue) - throw new LuaException("Unable to convert table value of type {0} to type {1}".F(kv.Value.WrappedClrType(), innerType)); + throw new LuaException($"Unable to convert table value of type {kv.Value.WrappedClrType()} to type {innerType}"); } array.SetValue(element, i++); @@ -186,7 +186,7 @@ namespace OpenRA.Scripting return table; } - throw new InvalidOperationException("Cannot convert type '{0}' to Lua. Class must implement IScriptBindable.".F(obj.GetType())); + throw new InvalidOperationException($"Cannot convert type '{obj.GetType()}' to Lua. Class must implement IScriptBindable."); } } } diff --git a/OpenRA.Game/Server/Server.cs b/OpenRA.Game/Server/Server.cs index ee14124f4e..c7c50cf6c3 100644 --- a/OpenRA.Game/Server/Server.cs +++ b/OpenRA.Game/Server/Server.cs @@ -494,7 +494,7 @@ namespace OpenRA.Server if (bans.Contains(client.IPAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint); - SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IPAddress) ? "banned" : "temporarily banned")); + SendOrderTo(newConn, "ServerError", $"You have been {(Settings.Ban.Contains(client.IPAddress) ? "banned" : "temporarily banned")} from the server"); DropClient(newConn); return; } @@ -543,7 +543,7 @@ namespace OpenRA.Server client.Name, newConn.Socket.RemoteEndPoint); // Report to all other players - SendMessage("{0} has joined the game.".F(client.Name), newConn); + SendMessage($"{client.Name} has joined the game.", newConn); // Send initial ping SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); @@ -816,7 +816,7 @@ namespace OpenRA.Server if (data.Length == Order.SyncHashOrderLength) HandleSyncOrder(frame, data); else - Log.Write("server", "Dropped sync order with length {0} from client {1}. Expected length {2}.".F(data.Length, from, Order.SyncHashOrderLength)); + Log.Write("server", $"Dropped sync order with length {data.Length} from client {from}. Expected length {Order.SyncHashOrderLength}."); } } } @@ -860,7 +860,7 @@ namespace OpenRA.Server DispatchOrdersToClients(conn, 0, Order.FromTargetString("Message", text, true).Serialize()); if (Type == ServerType.Dedicated) - Console.WriteLine("[{0}] {1}".F(DateTime.Now.ToString(Settings.TimestampFormat), text)); + Console.WriteLine($"[{DateTime.Now.ToString(Settings.TimestampFormat)}] {text}"); } void InterpretServerOrder(Connection conn, Order o) @@ -894,7 +894,7 @@ namespace OpenRA.Server if (handledBy == null) { Log.Write("server", "Unknown server command: {0}", o.TargetString); - SendOrderTo(conn, "Message", "Unknown server command: {0}".F(o.TargetString)); + SendOrderTo(conn, "Message", $"Unknown server command: {o.TargetString}"); } break; @@ -1070,8 +1070,8 @@ namespace OpenRA.Server var suffix = ""; if (State == ServerState.GameStarted) - suffix = dropClient.IsObserver ? " (Spectator)" : dropClient.Team != 0 ? " (Team {0})".F(dropClient.Team) : ""; - SendMessage("{0}{1} has disconnected.".F(dropClient.Name, suffix)); + suffix = dropClient.IsObserver ? " (Spectator)" : dropClient.Team != 0 ? $" (Team {dropClient.Team})" : ""; + SendMessage($"{dropClient.Name}{suffix} has disconnected."); // Send disconnected order, even if still in the lobby DispatchOrdersToClients(toDrop, 0, Order.FromTargetString("Disconnected", "", true).Serialize()); @@ -1098,7 +1098,7 @@ namespace OpenRA.Server if (nextAdmin != null) { nextAdmin.IsAdmin = true; - SendMessage("{0} is now the admin.".F(nextAdmin.Name)); + SendMessage($"{nextAdmin.Name} is now the admin."); } } diff --git a/OpenRA.Game/Settings.cs b/OpenRA.Game/Settings.cs index a0eafc43f4..e6495633c9 100644 --- a/OpenRA.Game/Settings.cs +++ b/OpenRA.Game/Settings.cs @@ -304,7 +304,7 @@ namespace OpenRA var err2 = FieldLoader.InvalidValueAction; try { - FieldLoader.UnknownFieldAction = (s, f) => Console.WriteLine("Ignoring unknown field `{0}` on `{1}`".F(s, f.Name)); + FieldLoader.UnknownFieldAction = (s, f) => Console.WriteLine($"Ignoring unknown field `{s}` on `{f.Name}`"); if (File.Exists(settingsFile)) { @@ -430,7 +430,7 @@ namespace OpenRA FieldLoader.InvalidValueAction = (s, t, f) => { var ret = defaults.GetType().GetField(f).GetValue(defaults); - Console.WriteLine("FieldLoader: Cannot parse `{0}` into `{2}:{1}`; substituting default `{3}`".F(s, t.Name, f, ret)); + Console.WriteLine($"FieldLoader: Cannot parse `{s}` into `{f}:{t.Name}`; substituting default `{ret}`"); return ret; }; diff --git a/OpenRA.Game/Sound/Sound.cs b/OpenRA.Game/Sound/Sound.cs index 254d261d57..a7789ad767 100644 --- a/OpenRA.Game/Sound/Sound.cs +++ b/OpenRA.Game/Sound/Sound.cs @@ -353,14 +353,14 @@ namespace OpenRA if (voicedActor != null) { if (!rules.VoicePools.Value.ContainsKey(definition)) - throw new InvalidOperationException("Can't find {0} in voice pool.".F(definition)); + throw new InvalidOperationException($"Can't find {definition} in voice pool."); pool = rules.VoicePools.Value[definition]; } else { if (!rules.NotificationsPools.Value.ContainsKey(definition)) - throw new InvalidOperationException("Can't find {0} in notification pool.".F(definition)); + throw new InvalidOperationException($"Can't find {definition} in notification pool."); pool = rules.NotificationsPools.Value[definition]; } diff --git a/OpenRA.Game/StreamExts.cs b/OpenRA.Game/StreamExts.cs index ea43497ab0..020e81e0cc 100644 --- a/OpenRA.Game/StreamExts.cs +++ b/OpenRA.Game/StreamExts.cs @@ -151,7 +151,7 @@ namespace OpenRA { var length = s.ReadInt32(); if (length > maxLength) - throw new InvalidOperationException("The length of the string ({0}) is longer than the maximum allowed ({1}).".F(length, maxLength)); + throw new InvalidOperationException($"The length of the string ({length}) is longer than the maximum allowed ({maxLength})."); return encoding.GetString(s.ReadBytes(length)); } diff --git a/OpenRA.Game/Support/Benchmark.cs b/OpenRA.Game/Support/Benchmark.cs index b426675f81..a2cc3089fc 100644 --- a/OpenRA.Game/Support/Benchmark.cs +++ b/OpenRA.Game/Support/Benchmark.cs @@ -46,11 +46,11 @@ namespace OpenRA.Support foreach (var sample in samples) { var name = sample.Key; - Log.AddChannel(name, "{0}{1}.csv".F(prefix, name)); + Log.AddChannel(name, $"{prefix}{name}.csv"); Log.Write(name, "tick,time [ms]"); foreach (var point in sample.Value) - Log.Write(name, "{0},{1}".F(point.Tick, point.Value)); + Log.Write(name, $"{point.Tick},{point.Value}"); } } diff --git a/OpenRA.Game/Support/Evaluator.cs b/OpenRA.Game/Support/Evaluator.cs index 559e0f289d..517f744a64 100644 --- a/OpenRA.Game/Support/Evaluator.cs +++ b/OpenRA.Game/Support/Evaluator.cs @@ -66,7 +66,7 @@ namespace OpenRA.Support else if (char.IsLetter(t[0])) { if (!syms.ContainsKey(t)) - throw new InvalidOperationException("Substitution `{0}` undefined".F(t)); + throw new InvalidOperationException($"Substitution `{t}` undefined"); yield return syms[t].ToString(); } diff --git a/OpenRA.Game/Support/Log.cs b/OpenRA.Game/Support/Log.cs index 3dd3d5c489..6894546537 100644 --- a/OpenRA.Game/Support/Log.cs +++ b/OpenRA.Game/Support/Log.cs @@ -121,9 +121,9 @@ namespace OpenRA Directory.CreateDirectory(path); for (var i = 0; i < CreateLogFileMaxRetryCount; i++) - yield return Path.Combine(path, i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename); + yield return Path.Combine(path, i > 0 ? $"{baseFilename}.{i}" : baseFilename); - throw new ApplicationException("Error creating log file \"{0}\"".F(baseFilename)); + throw new ApplicationException($"Error creating log file \"{baseFilename}\""); } static ChannelInfo GetChannel(string channelName) diff --git a/OpenRA.Game/Support/VariableExpression.cs b/OpenRA.Game/Support/VariableExpression.cs index ac7153e14f..5061d7b31a 100644 --- a/OpenRA.Game/Support/VariableExpression.cs +++ b/OpenRA.Game/Support/VariableExpression.cs @@ -287,8 +287,7 @@ namespace OpenRA.Support continue; } - throw new InvalidProgramException("CreateTokenTypeInfoEnumeration is missing a TokenTypeInfo entry for TokenType.{0}".F( - Enum.GetValues()[i])); + throw new InvalidProgramException($"CreateTokenTypeInfoEnumeration is missing a TokenTypeInfo entry for TokenType.{Enum.GetValues()[i]}"); } } @@ -355,8 +354,7 @@ namespace OpenRA.Support if (cc != CharClass.Digit) { if (cc != CharClass.Whitespace && cc != CharClass.Operator && cc != CharClass.Mixed) - throw new InvalidDataException("Number {0} and variable merged at index {1}".F( - int.Parse(expression.Substring(start, i - start)), start)); + throw new InvalidDataException($"Number {int.Parse(expression.Substring(start, i - start))} and variable merged at index {start}"); return true; } @@ -371,8 +369,7 @@ namespace OpenRA.Support static TokenType VariableOrKeyword(string expression, int start, ref int i) { if (CharClassOf(expression[i - 1]) == CharClass.Mixed) - throw new InvalidDataException("Invalid identifier end character at index {0} for `{1}`".F( - i - 1, expression.Substring(start, i - start))); + throw new InvalidDataException($"Invalid identifier end character at index {i - 1} for `{expression.Substring(start, i - start)}`"); return VariableOrKeyword(expression, start, i - start); } @@ -435,7 +432,7 @@ namespace OpenRA.Support return TokenType.Equals; } - throw new InvalidDataException("Unexpected character '=' at index {0} - should it be `==`?".F(start)); + throw new InvalidDataException($"Unexpected character '=' at index {start} - should it be `==`?"); case '&': i++; @@ -445,7 +442,7 @@ namespace OpenRA.Support return TokenType.And; } - throw new InvalidDataException("Unexpected character '&' at index {0} - should it be `&&`?".F(start)); + throw new InvalidDataException($"Unexpected character '&' at index {start} - should it be `&&`?"); case '|': i++; @@ -455,7 +452,7 @@ namespace OpenRA.Support return TokenType.Or; } - throw new InvalidDataException("Unexpected character '|' at index {0} - should it be `||`?".F(start)); + throw new InvalidDataException($"Unexpected character '|' at index {start} - should it be `||`?"); case '(': i++; @@ -500,7 +497,7 @@ namespace OpenRA.Support var cc = CharClassOf(expression[start]); if (cc != CharClass.Id) - throw new InvalidDataException("Invalid character '{0}' at index {1}".F(expression[i], start)); + throw new InvalidDataException($"Invalid character '{expression[i]}' at index {start}"); // Scan forwards until we find an invalid name character for (i = start; i < expression.Length; i++) @@ -532,15 +529,13 @@ namespace OpenRA.Support else if (lastType == TokenType.Invalid) whitespaceBefore = true; else if (RequiresWhitespaceAfter(lastType)) - throw new InvalidDataException("Missing whitespace at index {0}, after `{1}` operator." - .F(i, GetTokenSymbol(lastType))); + throw new InvalidDataException($"Missing whitespace at index {i}, after `{GetTokenSymbol(lastType)}` operator."); var start = i; var type = GetNextType(expression, ref i, lastType); if (!whitespaceBefore && RequiresWhitespaceBefore(type)) - throw new InvalidDataException("Missing whitespace at index {0}, before `{1}` operator." - .F(i, GetTokenSymbol(type))); + throw new InvalidDataException($"Missing whitespace at index {i}, before `{GetTokenSymbol(type)}` operator."); switch (type) { @@ -602,7 +597,7 @@ namespace OpenRA.Support // Expressions can't end with a binary or unary prefix operation if (lastToken.RightOperand) - throw new InvalidDataException("Missing value or sub-expression at end for `{0}` operator".F(lastToken.Symbol)); + throw new InvalidDataException($"Missing value or sub-expression at end for `{lastToken.Symbol}` operator"); break; } @@ -610,7 +605,7 @@ namespace OpenRA.Support if (token.Closes != Grouping.None) { if (currentOpeners.Count == 0) - throw new InvalidDataException("Unmatched closing parenthesis at index {0}".F(token.Index)); + throw new InvalidDataException($"Unmatched closing parenthesis at index {token.Index}"); currentOpeners.Pop(); } @@ -622,22 +617,20 @@ namespace OpenRA.Support { // Expressions can't start with a binary or unary postfix operation or closer if (token.LeftOperand) - throw new InvalidDataException("Missing value or sub-expression at beginning for `{0}` operator".F(token.Symbol)); + throw new InvalidDataException($"Missing value or sub-expression at beginning for `{token.Symbol}` operator"); } else { // Disallow empty parentheses if (lastToken.Opens != Grouping.None && token.Closes != Grouping.None) - throw new InvalidDataException("Empty parenthesis at index {0}".F(lastToken.Index)); + throw new InvalidDataException($"Empty parenthesis at index {lastToken.Index}"); // Exactly one of two consective tokens must take the other's sub-expression evaluation as an operand if (lastToken.RightOperand == token.LeftOperand) { if (lastToken.RightOperand) - throw new InvalidDataException( - "Missing value or sub-expression or there is an extra operator `{0}` at index {1} or `{2}` at index {3}".F( - lastToken.Symbol, lastToken.Index, token.Symbol, token.Index)); - throw new InvalidDataException("Missing binary operation before `{0}` at index {1}".F(token.Symbol, token.Index)); + throw new InvalidDataException($"Missing value or sub-expression or there is an extra operator `{lastToken.Symbol}` at index {lastToken.Index} or `{token.Symbol}` at index {token.Index}"); + throw new InvalidDataException($"Missing binary operation before `{token.Symbol}` at index {token.Index}"); } } @@ -649,7 +642,7 @@ namespace OpenRA.Support } if (currentOpeners.Count > 0) - throw new InvalidDataException("Unclosed opening parenthesis at index {0}".F(currentOpeners.Peek().Index)); + throw new InvalidDataException($"Unclosed opening parenthesis at index {currentOpeners.Peek().Index}"); return new Compiler().Build(ToPostfix(tokens).ToArray(), resultType); } @@ -743,8 +736,7 @@ namespace OpenRA.Support return IfThenElse(expression, One, Zero); } - throw new InvalidProgramException("Unable to convert ExpressionType.{0} to ExpressionType.{1}".F( - Enum.GetValues()[(int)fromType], Enum.GetValues()[(int)toType])); + throw new InvalidProgramException($"Unable to convert ExpressionType.{Enum.GetValues()[(int)fromType]} to ExpressionType.{Enum.GetValues()[(int)toType]}"); } public Expression Pop(ExpressionType type) @@ -760,11 +752,11 @@ namespace OpenRA.Support expressions.Add(expression); if (type == ExpressionType.Int) if (expression.Type != typeof(int)) - throw new InvalidOperationException("Expected System.Int type instead of {0} for {1}".F(expression.Type, expression)); + throw new InvalidOperationException($"Expected System.Int type instead of {expression.Type} for {expression}"); if (type == ExpressionType.Bool) if (expression.Type != typeof(bool)) - throw new InvalidOperationException("Expected System.Boolean type instead of {0} for {1}".F(expression.Type, expression)); + throw new InvalidOperationException($"Expected System.Boolean type instead of {expression.Type} for {expression}"); types.Add(type); } @@ -776,7 +768,7 @@ namespace OpenRA.Support else if (expression.Type == typeof(bool)) types.Add(ExpressionType.Bool); else - throw new InvalidOperationException("Unhandled result type {0} for {1}".F(expression.Type, expression)); + throw new InvalidOperationException($"Unhandled result type {expression.Type} for {expression}"); } } @@ -943,9 +935,7 @@ namespace OpenRA.Support } default: - throw new InvalidProgramException( - "ConditionExpression.Compiler.Compile() is missing an expression builder for TokenType.{0}".F( - Enum.GetValues()[(int)t.Type])); + throw new InvalidProgramException($"ConditionExpression.Compiler.Compile() is missing an expression builder for TokenType.{Enum.GetValues()[(int)t.Type]}"); } } diff --git a/OpenRA.Game/Sync.cs b/OpenRA.Game/Sync.cs index ad0cb86f51..dd42a0208f 100644 --- a/OpenRA.Game/Sync.cs +++ b/OpenRA.Game/Sync.cs @@ -69,14 +69,14 @@ namespace OpenRA il.MarkLabel(l); } else if (type != typeof(int)) - throw new NotImplementedException("SyncAttribute on member of unhashable type: {0}".F(type.FullName)); + throw new NotImplementedException($"SyncAttribute on member of unhashable type: {type.FullName}"); il.Emit(OpCodes.Xor); } static Func GenerateHashFunc(Type t) { - var d = new DynamicMethod("hash_{0}".F(t.Name), typeof(int), new Type[] { typeof(object) }, t); + var d = new DynamicMethod($"hash_{t.Name}", typeof(int), new Type[] { typeof(object) }, t); var il = d.GetILGenerator(); var this_ = il.DeclareLocal(t).LocalIndex; il.Emit(OpCodes.Ldarg_0); diff --git a/OpenRA.Game/TraitDictionary.cs b/OpenRA.Game/TraitDictionary.cs index c80ddc4735..1c01b7c7b1 100644 --- a/OpenRA.Game/TraitDictionary.cs +++ b/OpenRA.Game/TraitDictionary.cs @@ -81,7 +81,7 @@ namespace OpenRA static void CheckDestroyed(Actor actor) { if (actor.Disposed) - throw new InvalidOperationException("Attempted to get trait from destroyed object ({0})".F(actor)); + throw new InvalidOperationException($"Attempted to get trait from destroyed object ({actor})"); } public T Get(Actor actor) @@ -160,7 +160,7 @@ namespace OpenRA { var result = GetOrDefault(actor); if (result == null) - throw new InvalidOperationException("Actor {0} does not have trait of type `{1}`".F(actor.Info.Name, typeof(T))); + throw new InvalidOperationException($"Actor {actor.Info.Name} does not have trait of type `{typeof(T)}`"); return result; } @@ -173,7 +173,7 @@ namespace OpenRA return default; if (index + 1 < actors.Count && actors[index + 1] == actor) - throw new InvalidOperationException("Actor {0} has multiple traits of type `{1}`".F(actor.Info.Name, typeof(T))); + throw new InvalidOperationException($"Actor {actor.Info.Name} has multiple traits of type `{typeof(T)}`"); return traits[index]; } diff --git a/OpenRA.Game/Traits/Player/FrozenActorLayer.cs b/OpenRA.Game/Traits/Player/FrozenActorLayer.cs index 797b35a20b..f346d6338a 100644 --- a/OpenRA.Game/Traits/Player/FrozenActorLayer.cs +++ b/OpenRA.Game/Traits/Player/FrozenActorLayer.cs @@ -203,7 +203,7 @@ namespace OpenRA.Traits public override string ToString() { - return "{0} {1}{2}".F(Info.Name, ID, IsValid ? "" : " (invalid)"); + return $"{Info.Name} {ID}{(IsValid ? "" : " (invalid)")}"; } } diff --git a/OpenRA.Game/Traits/World/ScreenMap.cs b/OpenRA.Game/Traits/World/ScreenMap.cs index 66c7640aa7..ab13e0dea8 100644 --- a/OpenRA.Game/Traits/World/ScreenMap.cs +++ b/OpenRA.Game/Traits/World/ScreenMap.cs @@ -27,7 +27,7 @@ namespace OpenRA.Traits public override int GetHashCode() { return Actor.GetHashCode() ^ Bounds.GetHashCode(); } - public override string ToString() { return "{0}->{1}".F(Actor.Info.Name, Bounds.GetType().Name); } + public override string ToString() { return $"{Actor.Info.Name}->{Bounds.GetType().Name}"; } } [TraitLocation(SystemActors.World | SystemActors.EditorWorld)] diff --git a/OpenRA.Game/Translation.cs b/OpenRA.Game/Translation.cs index 7dffa411ea..3b889cd1a7 100644 --- a/OpenRA.Game/Translation.cs +++ b/OpenRA.Game/Translation.cs @@ -104,13 +104,13 @@ namespace OpenRA name = args[i] as string; if (string.IsNullOrEmpty(name)) { - throw new ArgumentException("Expected the argument at index {0} to be a non-empty string".F(i), + throw new ArgumentException($"Expected the argument at index {i} to be a non-empty string", nameof(args)); } value = args[i + 1]; if (value == null) - throw new ArgumentNullException("args", "Expected the argument at index {0} to be a non-null value".F(i + 1)); + throw new ArgumentNullException("args", $"Expected the argument at index {i + 1} to be a non-null value"); argumentDictionary.Add(name, value); } diff --git a/OpenRA.Game/WAngle.cs b/OpenRA.Game/WAngle.cs index 8f4c6e88a9..f96f62c1e2 100644 --- a/OpenRA.Game/WAngle.cs +++ b/OpenRA.Game/WAngle.cs @@ -85,7 +85,7 @@ namespace OpenRA public static WAngle ArcSin(int d) { if (d < -1024 || d > 1024) - throw new ArgumentException("ArcSin is only valid for values between -1024 and 1024. Received {0}".F(d)); + throw new ArgumentException($"ArcSin is only valid for values between -1024 and 1024. Received {d}"); var a = ClosestCosineIndex(Math.Abs(d)); return new WAngle(d < 0 ? 768 + a : 256 - a); @@ -94,7 +94,7 @@ namespace OpenRA public static WAngle ArcCos(int d) { if (d < -1024 || d > 1024) - throw new ArgumentException("ArcCos is only valid for values between -1024 and 1024. Received {0}".F(d)); + throw new ArgumentException($"ArcCos is only valid for values between -1024 and 1024. Received {d}"); var a = ClosestCosineIndex(Math.Abs(d)); return new WAngle(d < 0 ? 512 - a : a); @@ -222,7 +222,7 @@ namespace OpenRA public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out WAngle a)) - throw new LuaException("Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); if (right.TryGetClrValue(out int c)) { @@ -233,13 +233,13 @@ namespace OpenRA if (right.TryGetClrValue(out WAngle b)) return new LuaCustomClrObject(a + b); - throw new LuaException("Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WAngle.Add(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); } public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out WAngle a)) - throw new LuaException("Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); if (right.TryGetClrValue(out int c)) { @@ -250,7 +250,7 @@ namespace OpenRA if (right.TryGetClrValue(out WAngle b)) return new LuaCustomClrObject(a - b); - throw new LuaException("Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WAngle.Subtract(WAngle, WAngle) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); } public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) diff --git a/OpenRA.Game/WDist.cs b/OpenRA.Game/WDist.cs index 1d494afdba..8f6ee8ae89 100644 --- a/OpenRA.Game/WDist.cs +++ b/OpenRA.Game/WDist.cs @@ -144,7 +144,7 @@ namespace OpenRA { case "Length": return Length; case "Range": Game.Debug("WDist.Range is deprecated. Use WDist.Length instead"); return Length; - default: throw new LuaException("WDist does not define a member '{0}'".F(key)); + default: throw new LuaException($"WDist does not define a member '{key}'"); } } diff --git a/OpenRA.Game/WPos.cs b/OpenRA.Game/WPos.cs index 0ae9c2de59..3d986574ee 100644 --- a/OpenRA.Game/WPos.cs +++ b/OpenRA.Game/WPos.cs @@ -83,7 +83,7 @@ namespace OpenRA public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out WPos a) || !right.TryGetClrValue(out WVec b)) - throw new LuaException("Attempted to call WPos.Add(WPos, WVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WPos.Add(WPos, WVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); return new LuaCustomClrObject(a + b); } @@ -92,7 +92,7 @@ namespace OpenRA { var rightType = right.WrappedClrType(); if (!left.TryGetClrValue(out WPos a)) - throw new LuaException("Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); + throw new LuaException($"Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})"); if (rightType == typeof(WPos)) { @@ -105,7 +105,7 @@ namespace OpenRA return new LuaCustomClrObject(a - b); } - throw new LuaException("Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, rightType.Name)); + throw new LuaException($"Attempted to call WPos.Subtract(WPos, (WPos|WVec)) with invalid arguments ({left.WrappedClrType().Name}, {rightType.Name})"); } public LuaValue Equals(LuaRuntime runtime, LuaValue left, LuaValue right) @@ -125,7 +125,7 @@ namespace OpenRA case "X": return X; case "Y": return Y; case "Z": return Z; - default: throw new LuaException("WPos does not define a member '{0}'".F(key)); + default: throw new LuaException($"WPos does not define a member '{key}'"); } } diff --git a/OpenRA.Game/WVec.cs b/OpenRA.Game/WVec.cs index f398e24fe6..609ba97e13 100644 --- a/OpenRA.Game/WVec.cs +++ b/OpenRA.Game/WVec.cs @@ -111,7 +111,7 @@ namespace OpenRA public LuaValue Add(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out WVec a) || !right.TryGetClrValue(out WVec b)) - throw new LuaException("Attempted to call WVec.Add(WVec, WVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WVec.Add(WVec, WVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); return new LuaCustomClrObject(a + b); } @@ -119,7 +119,7 @@ namespace OpenRA public LuaValue Subtract(LuaRuntime runtime, LuaValue left, LuaValue right) { if (!left.TryGetClrValue(out WVec a) || !right.TryGetClrValue(out WVec b)) - throw new LuaException("Attempted to call WVec.Subtract(WVec, WVec) with invalid arguments ({0}, {1})".F(left.WrappedClrType().Name, right.WrappedClrType().Name)); + throw new LuaException($"Attempted to call WVec.Subtract(WVec, WVec) with invalid arguments ({left.WrappedClrType().Name}, {right.WrappedClrType().Name})"); return new LuaCustomClrObject(a - b); } @@ -147,7 +147,7 @@ namespace OpenRA case "Y": return Y; case "Z": return Z; case "Facing": return new LuaCustomClrObject(Yaw); - default: throw new LuaException("WVec does not define a member '{0}'".F(key)); + default: throw new LuaException($"WVec does not define a member '{key}'"); } } diff --git a/OpenRA.Game/Widgets/Widget.cs b/OpenRA.Game/Widgets/Widget.cs index e1e301e734..08fc35c2b3 100644 --- a/OpenRA.Game/Widgets/Widget.cs +++ b/OpenRA.Game/Widgets/Widget.cs @@ -80,7 +80,7 @@ namespace OpenRA.Widgets if (LoadWidget(id, parent, args) is T widget) return widget; - throw new InvalidOperationException("Widget {0} is not of type {1}".F(id, typeof(T).Name)); + throw new InvalidOperationException($"Widget {id} is not of type {typeof(T).Name}"); } public static Widget LoadWidget(string id, Widget parent, WidgetArgs args) @@ -236,7 +236,7 @@ namespace OpenRA.Widgets public virtual Widget Clone() { - throw new InvalidOperationException("Widget type `{0}` is not cloneable.".F(GetType().Name)); + throw new InvalidOperationException($"Widget type `{GetType().Name}` is not cloneable."); } public virtual int2 RenderOrigin @@ -579,9 +579,7 @@ namespace OpenRA.Widgets { var t = GetOrNull(id); if (t == null) - throw new InvalidOperationException( - "Widget {0} has no child {1} of type {2}".F( - Id, id, typeof(T).Name)); + throw new InvalidOperationException($"Widget {Id} has no child {id} of type {typeof(T).Name}"); return t; } diff --git a/OpenRA.Game/Widgets/WidgetLoader.cs b/OpenRA.Game/Widgets/WidgetLoader.cs index 9fdbbafd45..dc08c45a48 100644 --- a/OpenRA.Game/Widgets/WidgetLoader.cs +++ b/OpenRA.Game/Widgets/WidgetLoader.cs @@ -30,7 +30,7 @@ namespace OpenRA { var key = w.Key.Substring(w.Key.IndexOf('@') + 1); if (widgets.ContainsKey(key)) - throw new InvalidDataException("Widget has duplicate Key `{0}` at {1}".F(w.Key, w.Location)); + throw new InvalidDataException($"Widget has duplicate Key `{w.Key}` at {w.Location}"); widgets.Add(key, w); } } @@ -38,7 +38,7 @@ namespace OpenRA public Widget LoadWidget(WidgetArgs args, Widget parent, string w) { if (!widgets.TryGetValue(w, out var ret)) - throw new InvalidDataException("Cannot find widget with Id `{0}`".F(w)); + throw new InvalidDataException($"Cannot find widget with Id `{w}`"); return LoadWidget(args, parent, ret); } diff --git a/OpenRA.Mods.Cnc/Activities/Teleport.cs b/OpenRA.Mods.Cnc/Activities/Teleport.cs index 57d873aac6..0b6982a365 100644 --- a/OpenRA.Mods.Cnc/Activities/Teleport.cs +++ b/OpenRA.Mods.Cnc/Activities/Teleport.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Cnc.Activities { var max = teleporter.World.Map.Grid.MaximumTileSearchRange; if (maximumDistance > max) - throw new InvalidOperationException("Teleport distance cannot exceed the value of MaximumTileSearchRange ({0}).".F(max)); + throw new InvalidOperationException($"Teleport distance cannot exceed the value of MaximumTileSearchRange ({max})."); this.teleporter = teleporter; this.destination = destination; diff --git a/OpenRA.Mods.Cnc/FileFormats/HvaReader.cs b/OpenRA.Mods.Cnc/FileFormats/HvaReader.cs index 8714ce7860..b77d611735 100644 --- a/OpenRA.Mods.Cnc/FileFormats/HvaReader.cs +++ b/OpenRA.Mods.Cnc/FileFormats/HvaReader.cs @@ -50,8 +50,7 @@ namespace OpenRA.Mods.Cnc.FileFormats Array.Copy(Transforms, 16 * (LimbCount * j + i), testMatrix, 0, 16); if (OpenRA.Graphics.Util.MatrixInverse(testMatrix) == null) throw new InvalidDataException( - "The transformation matrix for HVA file `{0}` section {1} frame {2} is invalid because it is not invertible!" - .F(fileName, i, j)); + $"The transformation matrix for HVA file `{fileName}` section {i} frame {j} is invalid because it is not invertible!"); } } diff --git a/OpenRA.Mods.Cnc/FileFormats/IdxEntry.cs b/OpenRA.Mods.Cnc/FileFormats/IdxEntry.cs index 7acb2ba9e9..102a2ee08b 100644 --- a/OpenRA.Mods.Cnc/FileFormats/IdxEntry.cs +++ b/OpenRA.Mods.Cnc/FileFormats/IdxEntry.cs @@ -39,7 +39,7 @@ namespace OpenRA.Mods.Cnc.FileFormats public override string ToString() { - return "{0} - offset 0x{1:x8} - length 0x{2:x8}".F(Filename, Offset, Length); + return $"{Filename} - offset 0x{Offset:x8} - length 0x{Length:x8}"; } } } diff --git a/OpenRA.Mods.Cnc/FileFormats/IdxReader.cs b/OpenRA.Mods.Cnc/FileFormats/IdxReader.cs index b0440f1d1d..722f6ba269 100644 --- a/OpenRA.Mods.Cnc/FileFormats/IdxReader.cs +++ b/OpenRA.Mods.Cnc/FileFormats/IdxReader.cs @@ -26,12 +26,12 @@ namespace OpenRA.Mods.Cnc.FileFormats var id = s.ReadASCII(4); if (id != "GABA") - throw new InvalidDataException("Unable to load Idx file, did not find magic id, found {0} instead".F(id)); + throw new InvalidDataException($"Unable to load Idx file, did not find magic id, found {id} instead"); var two = s.ReadInt32(); if (two != 2) - throw new InvalidDataException("Unable to load Idx file, did not find magic number 2, found {0} instead".F(two)); + throw new InvalidDataException($"Unable to load Idx file, did not find magic number 2, found {two} instead"); SoundCount = s.ReadInt32(); diff --git a/OpenRA.Mods.Cnc/FileFormats/LCWCompression.cs b/OpenRA.Mods.Cnc/FileFormats/LCWCompression.cs index 0fe782485a..65f0837f45 100644 --- a/OpenRA.Mods.Cnc/FileFormats/LCWCompression.cs +++ b/OpenRA.Mods.Cnc/FileFormats/LCWCompression.cs @@ -21,7 +21,7 @@ namespace OpenRA.Mods.Cnc.FileFormats static void ReplicatePrevious(byte[] dest, int destIndex, int srcIndex, int count) { if (srcIndex > destIndex) - throw new NotImplementedException("srcIndex > destIndex {0} {1}".F(srcIndex, destIndex)); + throw new NotImplementedException($"srcIndex > destIndex {srcIndex} {destIndex}"); for (var i = 0; i < count; i++) { @@ -80,7 +80,7 @@ namespace OpenRA.Mods.Cnc.FileFormats var count = count3 == 0x3F ? ctx.ReadWord() : count3 + 3; var srcIndex = reverse ? destIndex - ctx.ReadWord() : ctx.ReadWord(); if (srcIndex >= destIndex) - throw new NotImplementedException("srcIndex >= destIndex {0} {1}".F(srcIndex, destIndex)); + throw new NotImplementedException($"srcIndex >= destIndex {srcIndex} {destIndex}"); for (var end = destIndex + count; destIndex < end; destIndex++) dest[destIndex] = dest[srcIndex++]; diff --git a/OpenRA.Mods.Cnc/FileFormats/VqaReader.cs b/OpenRA.Mods.Cnc/FileFormats/VqaReader.cs index 896fdec9cc..52bd37d052 100644 --- a/OpenRA.Mods.Cnc/FileFormats/VqaReader.cs +++ b/OpenRA.Mods.Cnc/FileFormats/VqaReader.cs @@ -142,7 +142,7 @@ namespace OpenRA.Mods.Cnc.FileFormats type = stream.ReadASCII(4); } else - throw new NotSupportedException("Vqa uses unknown Subtype: {0}".F(type)); + throw new NotSupportedException($"Vqa uses unknown Subtype: {type}"); } /*var length = */stream.ReadUInt16(); @@ -217,7 +217,7 @@ namespace OpenRA.Mods.Cnc.FileFormats break; default: if (length + stream.Position > stream.Length) - throw new NotSupportedException("Vqa uses unknown Subtype: {0}".F(type)); + throw new NotSupportedException($"Vqa uses unknown Subtype: {type}"); stream.ReadBytes((int)length); break; } @@ -420,7 +420,7 @@ namespace OpenRA.Mods.Cnc.FileFormats vtprSize = subchunkLength; return; default: - throw new InvalidDataException("Unknown sub-chunk {0}".F(type)); + throw new InvalidDataException($"Unknown sub-chunk {type}"); } } } @@ -562,7 +562,7 @@ namespace OpenRA.Mods.Cnc.FileFormats // Replicate previous var srcIndex = destIndex - rpos; if (srcIndex > destIndex) - throw new NotImplementedException("srcIndex > destIndex {0} {1}".F(srcIndex, destIndex)); + throw new NotImplementedException($"srcIndex > destIndex {srcIndex} {destIndex}"); for (var j = 0; j < count; j++) { @@ -602,7 +602,7 @@ namespace OpenRA.Mods.Cnc.FileFormats var count = count3 == 0x3F ? ctx.ReadWord() : count3 + 3; var srcIndex = reverse ? destIndex - ctx.ReadWord() : ctx.ReadWord(); if (srcIndex >= destIndex) - throw new NotImplementedException("srcIndex >= destIndex {0} {1}".F(srcIndex, destIndex)); + throw new NotImplementedException($"srcIndex >= destIndex {srcIndex} {destIndex}"); for (var end = destIndex + count; destIndex < end; destIndex++) dest[destIndex] = dest[srcIndex++]; diff --git a/OpenRA.Mods.Cnc/FileSystem/MixFile.cs b/OpenRA.Mods.Cnc/FileSystem/MixFile.cs index f13270f3a4..95fd6a8f5e 100644 --- a/OpenRA.Mods.Cnc/FileSystem/MixFile.cs +++ b/OpenRA.Mods.Cnc/FileSystem/MixFile.cs @@ -54,8 +54,8 @@ namespace OpenRA.Mods.Cnc.FileSystem entries = ParseHeader(s, isCncMix ? 0 : 4, out dataStart); index = ParseIndex(entries.ToDictionaryWithConflictLog(x => x.Hash, - "{0} ({1} format, Encrypted: {2}, DataStart: {3})".F(filename, isCncMix ? "C&C" : "RA/TS/RA2", isEncrypted, dataStart), - null, x => "(offs={0}, len={1})".F(x.Offset, x.Length)), allPossibleFilenames); + $"{filename} ({(isCncMix ? "C&C" : "RA/TS/RA2")} format, Encrypted: {isEncrypted}, DataStart: {dataStart})", + null, x => $"(offs={x.Offset}, len={x.Length})"), allPossibleFilenames); } catch (Exception) { @@ -103,7 +103,7 @@ namespace OpenRA.Mods.Cnc.FileSystem var unknown = entries.Count - bestIndex.Count; if (unknown > 0) - Log.Write("debug", "{0}: failed to resolve filenames for {1} unknown hashes".F(Name, unknown)); + Log.Write("debug", $"{Name}: failed to resolve filenames for {unknown} unknown hashes"); return bestIndex; } @@ -165,7 +165,7 @@ namespace OpenRA.Mods.Cnc.FileSystem throw new ArgumentOutOfRangeException(nameof(count), "Non-negative number required."); if (offset + (count * 2) > s.Length) - throw new ArgumentException("Bytes to read {0} and offset {1} greater than stream length {2}.".F(count * 2, offset, s.Length)); + throw new ArgumentException($"Bytes to read {count * 2} and offset {offset} greater than stream length {s.Length}."); s.Seek(offset, SeekOrigin.Begin); diff --git a/OpenRA.Mods.Cnc/FileSystem/PackageEntry.cs b/OpenRA.Mods.Cnc/FileSystem/PackageEntry.cs index 76030064e5..5081a87af3 100644 --- a/OpenRA.Mods.Cnc/FileSystem/PackageEntry.cs +++ b/OpenRA.Mods.Cnc/FileSystem/PackageEntry.cs @@ -50,9 +50,9 @@ namespace OpenRA.Mods.Cnc.FileSystem public override string ToString() { if (names.TryGetValue(Hash, out var filename)) - return "{0} - offset 0x{1:x8} - length 0x{2:x8}".F(filename, Offset, Length); + return $"{filename} - offset 0x{Offset:x8} - length 0x{Length:x8}"; else - return "0x{0:x8} - offset 0x{1:x8} - length 0x{2:x8}".F(Hash, Offset, Length); + return $"0x{Hash:x8} - offset 0x{Offset:x8} - length 0x{Length:x8}"; } public static uint HashFilename(string name, PackageHashType type) @@ -93,7 +93,7 @@ namespace OpenRA.Mods.Cnc.FileSystem return CRC32.Calculate(Encoding.ASCII.GetBytes(name)); } - default: throw new NotImplementedException("Unknown hash type `{0}`".F(type)); + default: throw new NotImplementedException($"Unknown hash type `{type}`"); } } diff --git a/OpenRA.Mods.Cnc/Graphics/ClassicSpriteSequence.cs b/OpenRA.Mods.Cnc/Graphics/ClassicSpriteSequence.cs index 827e7d09b4..2f2da00a3e 100644 --- a/OpenRA.Mods.Cnc/Graphics/ClassicSpriteSequence.cs +++ b/OpenRA.Mods.Cnc/Graphics/ClassicSpriteSequence.cs @@ -38,8 +38,7 @@ namespace OpenRA.Mods.Cnc.Graphics if (useClassicFacings && Facings != 32) throw new InvalidOperationException( - "{0}: Sequence {1}.{2}: UseClassicFacings is only valid for 32 facings" - .F(info.Nodes[0].Location, sequence, animation)); + $"{info.Nodes[0].Location}: Sequence {sequence}.{animation}: UseClassicFacings is only valid for 32 facings"); } protected override int GetFacingFrameOffset(WAngle facing) diff --git a/OpenRA.Mods.Cnc/Graphics/Voxel.cs b/OpenRA.Mods.Cnc/Graphics/Voxel.cs index f09e274210..965b02a994 100644 --- a/OpenRA.Mods.Cnc/Graphics/Voxel.cs +++ b/OpenRA.Mods.Cnc/Graphics/Voxel.cs @@ -38,7 +38,7 @@ namespace OpenRA.Mods.Cnc.Graphics public Voxel(VoxelLoader loader, VxlReader vxl, HvaReader hva, (string Vxl, string Hva) files) { if (vxl.LimbCount != hva.LimbCount) - throw new InvalidOperationException("{0}.vxl and {1}.hva limb counts don't match.".F(files.Vxl, files.Hva)); + throw new InvalidOperationException($"{files.Vxl}.vxl and {files.Hva}.hva limb counts don't match."); transforms = hva.Transforms; frames = hva.FrameCount; @@ -60,9 +60,9 @@ namespace OpenRA.Mods.Cnc.Graphics public float[] TransformationMatrix(uint limb, uint frame) { if (frame >= frames) - throw new ArgumentOutOfRangeException(nameof(frame), "Only {0} frames exist.".F(frames)); + throw new ArgumentOutOfRangeException(nameof(frame), $"Only {frames} frames exist."); if (limb >= limbs) - throw new ArgumentOutOfRangeException(nameof(limb), "Only {1} limbs exist.".F(limbs)); + throw new ArgumentOutOfRangeException(nameof(limb), $"Only {limbs} limbs exist."); var l = limbData[limb]; var t = new float[16]; diff --git a/OpenRA.Mods.Cnc/Graphics/VoxelModelSequenceLoader.cs b/OpenRA.Mods.Cnc/Graphics/VoxelModelSequenceLoader.cs index 1283b666d9..f7a883b463 100644 --- a/OpenRA.Mods.Cnc/Graphics/VoxelModelSequenceLoader.cs +++ b/OpenRA.Mods.Cnc/Graphics/VoxelModelSequenceLoader.cs @@ -98,10 +98,10 @@ namespace OpenRA.Mods.Cnc.Graphics { if (models.ContainsKey(model)) throw new InvalidOperationException( - "Model `{0}` does not have a sequence `{1}`".F(model, sequence)); + $"Model `{model}` does not have a sequence `{sequence}`"); else throw new InvalidOperationException( - "Model `{0}` does not have any sequences defined.".F(model)); + $"Model `{model}` does not have any sequences defined."); } } @@ -109,7 +109,7 @@ namespace OpenRA.Mods.Cnc.Graphics { if (!models.ContainsKey(model)) throw new InvalidOperationException( - "Model `{0}` does not have any sequences defined.".F(model)); + $"Model `{model}` does not have any sequences defined."); return models[model].ContainsKey(sequence); } diff --git a/OpenRA.Mods.Cnc/Scripting/Properties/ChronosphereProperties.cs b/OpenRA.Mods.Cnc/Scripting/Properties/ChronosphereProperties.cs index b65d00c9b6..2dedf5067b 100644 --- a/OpenRA.Mods.Cnc/Scripting/Properties/ChronosphereProperties.cs +++ b/OpenRA.Mods.Cnc/Scripting/Properties/ChronosphereProperties.cs @@ -33,8 +33,7 @@ namespace OpenRA.Mods.Cnc.Scripting using (kv.Value) { if (!kv.Key.TryGetClrValue(out actor) || !kv.Value.TryGetClrValue(out cell)) - throw new LuaException("Chronoshift requires a table of Actor,CPos pairs. Received {0},{1}".F( - kv.Key.WrappedClrType().Name, kv.Value.WrappedClrType().Name)); + throw new LuaException($"Chronoshift requires a table of Actor,CPos pairs. Received {kv.Key.WrappedClrType().Name},{kv.Value.WrappedClrType().Name}"); } var cs = actor.TraitsImplementing() diff --git a/OpenRA.Mods.Cnc/Scripting/Properties/InfiltrateProperties.cs b/OpenRA.Mods.Cnc/Scripting/Properties/InfiltrateProperties.cs index 58335dc88c..4a575f34a9 100644 --- a/OpenRA.Mods.Cnc/Scripting/Properties/InfiltrateProperties.cs +++ b/OpenRA.Mods.Cnc/Scripting/Properties/InfiltrateProperties.cs @@ -35,7 +35,7 @@ namespace OpenRA.Mods.Cnc.Scripting var infiltrates = infiltratesTraits.FirstOrDefault(x => !x.IsTraitDisabled && x.Info.Types.Overlaps(target.GetEnabledTargetTypes())); if (infiltrates == null) - throw new LuaException("{0} tried to infiltrate invalid target {1}!".F(Self, target)); + throw new LuaException($"{Self} tried to infiltrate invalid target {target}!"); // NB: Scripted actions get no visible targetlines. Self.QueueActivity(new Infiltrate(Self, Target.FromActor(target), infiltrates, null)); diff --git a/OpenRA.Mods.Cnc/SpriteLoaders/ShpRemasteredLoader.cs b/OpenRA.Mods.Cnc/SpriteLoaders/ShpRemasteredLoader.cs index 7f29925856..71349a304a 100644 --- a/OpenRA.Mods.Cnc/SpriteLoaders/ShpRemasteredLoader.cs +++ b/OpenRA.Mods.Cnc/SpriteLoaders/ShpRemasteredLoader.cs @@ -75,7 +75,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders framePrefix = prefix; if (prefix != framePrefix) - throw new InvalidDataException("Frame prefix mismatch: `{0}` != `{1}`".F(prefix, framePrefix)); + throw new InvalidDataException($"Frame prefix mismatch: `{prefix}` != `{framePrefix}`"); frameCount = Math.Max(frameCount, int.Parse(match.Groups["frame"].Value) + 1); } @@ -83,7 +83,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders var frames = new ISpriteFrame[frameCount]; for (var i = 0; i < frames.Length; i++) { - var tgaEntry = container.GetEntry("{0}{1:D4}.tga".F(framePrefix, i)); + var tgaEntry = container.GetEntry($"{framePrefix}{i:D4}.tga"); // Blank frame if (tgaEntry == null) @@ -92,7 +92,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders continue; } - var metaEntry = container.GetEntry("{0}{1:D4}.meta".F(framePrefix, i)); + var metaEntry = container.GetEntry($"{framePrefix}{i:D4}.meta"); using (var tgaStream = container.GetInputStream(tgaEntry)) { var metaStream = metaEntry != null ? container.GetInputStream(metaEntry) : null; diff --git a/OpenRA.Mods.Cnc/SpriteLoaders/ShpTDLoader.cs b/OpenRA.Mods.Cnc/SpriteLoaders/ShpTDLoader.cs index 3075ccc5ff..8fc6b4fbb0 100644 --- a/OpenRA.Mods.Cnc/SpriteLoaders/ShpTDLoader.cs +++ b/OpenRA.Mods.Cnc/SpriteLoaders/ShpTDLoader.cs @@ -147,7 +147,7 @@ namespace OpenRA.Mods.Cnc.SpriteLoaders if (h.Format == Format.XORPrev) h.RefImage = headers[i - 1]; else if (h.Format == Format.XORLCW && !offsets.TryGetValue(h.RefOffset, out h.RefImage)) - throw new InvalidDataException("Reference doesn't point to image data {0}->{1}".F(h.FileOffset, h.RefOffset)); + throw new InvalidDataException($"Reference doesn't point to image data {h.FileOffset}->{h.RefOffset}"); } shpBytesFileOffset = stream.Position; diff --git a/OpenRA.Mods.Cnc/Traits/EnergyWall.cs b/OpenRA.Mods.Cnc/Traits/EnergyWall.cs index ff27dca357..55d4c72b39 100644 --- a/OpenRA.Mods.Cnc/Traits/EnergyWall.cs +++ b/OpenRA.Mods.Cnc/Traits/EnergyWall.cs @@ -38,7 +38,7 @@ namespace OpenRA.Mods.Cnc.Traits { var weaponToLower = Weapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weaponInfo)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weaponInfo; } diff --git a/OpenRA.Mods.Cnc/Traits/MadTank.cs b/OpenRA.Mods.Cnc/Traits/MadTank.cs index df488a2aca..eb706a9c77 100644 --- a/OpenRA.Mods.Cnc/Traits/MadTank.cs +++ b/OpenRA.Mods.Cnc/Traits/MadTank.cs @@ -77,10 +77,10 @@ namespace OpenRA.Mods.Cnc.Traits var detonationWeaponToLower = (DetonationWeapon ?? string.Empty).ToLowerInvariant(); if (!rules.Weapons.TryGetValue(thumpDamageWeaponToLower, out var thumpDamageWeapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(thumpDamageWeaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{thumpDamageWeaponToLower}'"); if (!rules.Weapons.TryGetValue(detonationWeaponToLower, out var detonationWeapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(detonationWeaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{detonationWeaponToLower}'"); ThumpDamageWeaponInfo = thumpDamageWeapon; DetonationWeaponInfo = detonationWeapon; diff --git a/OpenRA.Mods.Cnc/Traits/Minelayer.cs b/OpenRA.Mods.Cnc/Traits/Minelayer.cs index a222eed917..b48758c66a 100644 --- a/OpenRA.Mods.Cnc/Traits/Minelayer.cs +++ b/OpenRA.Mods.Cnc/Traits/Minelayer.cs @@ -81,8 +81,8 @@ namespace OpenRA.Mods.Cnc.Traits this.self = self; var tileset = self.World.Map.Tileset.ToLowerInvariant(); - if (self.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(Info.TileValidName, tileset))) - Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(Info.TileValidName, tileset)).GetSprite(0); + if (self.World.Map.Rules.Sequences.HasSequence("overlay", $"{Info.TileValidName}-{tileset}")) + Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", $"{Info.TileValidName}-{tileset}").GetSprite(0); else Tile = self.World.Map.Rules.Sequences.GetSequence("overlay", Info.TileValidName).GetSprite(0); } @@ -220,9 +220,9 @@ namespace OpenRA.Mods.Cnc.Traits minelayer = a.Trait(); var tileset = a.World.Map.Tileset.ToLowerInvariant(); - if (a.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(minelayer.Info.TileValidName, tileset))) + if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileValidName}-{tileset}")) { - var validSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(minelayer.Info.TileValidName, tileset)); + var validSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileValidName}-{tileset}"); validTile = validSequence.GetSprite(0); validAlpha = validSequence.GetAlpha(0); } @@ -233,9 +233,9 @@ namespace OpenRA.Mods.Cnc.Traits validAlpha = validSequence.GetAlpha(0); } - if (a.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(minelayer.Info.TileUnknownName, tileset))) + if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileUnknownName}-{tileset}")) { - var unknownSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(minelayer.Info.TileUnknownName, tileset)); + var unknownSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileUnknownName}-{tileset}"); unknownTile = unknownSequence.GetSprite(0); unknownAlpha = unknownSequence.GetAlpha(0); } @@ -246,9 +246,9 @@ namespace OpenRA.Mods.Cnc.Traits unknownAlpha = unknownSequence.GetAlpha(0); } - if (a.World.Map.Rules.Sequences.HasSequence("overlay", "{0}-{1}".F(minelayer.Info.TileInvalidName, tileset))) + if (a.World.Map.Rules.Sequences.HasSequence("overlay", $"{minelayer.Info.TileInvalidName}-{tileset}")) { - var blockedSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", "{0}-{1}".F(minelayer.Info.TileInvalidName, tileset)); + var blockedSequence = a.World.Map.Rules.Sequences.GetSequence("overlay", $"{minelayer.Info.TileInvalidName}-{tileset}"); blockedTile = blockedSequence.GetSprite(0); blockedAlpha = blockedSequence.GetAlpha(0); } diff --git a/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs b/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs index 60454d98b5..ffebf6b090 100644 --- a/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs +++ b/OpenRA.Mods.Cnc/Traits/SupportPowers/DropPodsPower.cs @@ -68,7 +68,7 @@ namespace OpenRA.Mods.Cnc.Traits { var weaponToLower = (Weapon ?? string.Empty).ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weapon; diff --git a/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs b/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs index 909b90fb10..f6cded299f 100644 --- a/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs +++ b/OpenRA.Mods.Cnc/Traits/SupportPowers/IonCannonPower.cs @@ -54,7 +54,7 @@ namespace OpenRA.Mods.Cnc.Traits { var weaponToLower = (Weapon ?? string.Empty).ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weapon; diff --git a/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs b/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs index ff2227a9fb..895c800f43 100644 --- a/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs +++ b/OpenRA.Mods.Cnc/Traits/World/TSVeinsRenderer.cs @@ -249,7 +249,7 @@ namespace OpenRA.Mods.Cnc.Traits else if (BorderIndices.TryGetValue(adjacency, out var indices)) UpdateSpriteLayers(cell, indices); else - throw new InvalidOperationException("SpriteMap does not contain an index for Adjacency type '{0}'".F(adjacency)); + throw new InvalidOperationException($"SpriteMap does not contain an index for Adjacency type '{adjacency}'"); } void UpdateSpriteLayers(CPos cell, int[] indices) diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs index ac223e0588..9a535b8681 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportRedAlertLegacyMapCommand.cs @@ -36,7 +36,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands { if (format < 2) { - Console.WriteLine("ERROR: Detected NewINIFormat {0}. Are you trying to import a Tiberian Dawn map?".F(format)); + Console.WriteLine($"ERROR: Detected NewINIFormat {format}. Are you trying to import a Tiberian Dawn map?"); return; } } diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs index 9ce3f232eb..c4059e0169 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportTSMapCommand.cs @@ -270,7 +270,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands var size = new Size(iniSize[2], 2 * iniSize[3]); if (!utility.ModData.DefaultTerrainInfo.TryGetValue(tileset, out var terrainInfo)) - throw new InvalidDataException("Unknown tileset {0}".F(tileset)); + throw new InvalidDataException($"Unknown tileset {tileset}"); var map = new Map(Game.ModData, terrainInfo, size.Width, size.Height) { @@ -527,7 +527,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands ar.Add(new OwnerInit("Neutral")); if (!map.Rules.Actors.ContainsKey(name)) - Console.WriteLine("Ignoring unknown actor type: `{0}`".F(name)); + Console.WriteLine($"Ignoring unknown actor type: `{name}`"); else map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save())); } @@ -573,7 +573,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands ar.Add(new DeployStateInit(DeployState.Deployed)); if (!map.Rules.Actors.ContainsKey(name)) - Console.WriteLine("Ignoring unknown actor type: `{0}`".F(name)); + Console.WriteLine($"Ignoring unknown actor type: `{name}`"); else map.ActorDefinitions.Add(new MiniYamlNode("Actor" + map.ActorDefinitions.Count, ar.Save())); } @@ -600,7 +600,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands if (lightingTypes.ContainsKey(kv.Key)) parsed[kv.Key] = FieldLoader.GetValue(kv.Key, kv.Value); else - Console.WriteLine("Ignoring unknown lighting type: `{0}`".F(kv.Key)); + Console.WriteLine($"Ignoring unknown lighting type: `{kv.Key}`"); } // Merge Ground into Ambient diff --git a/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs b/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs index 0ec64a0784..66dde0f2c1 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/ImportTiberianDawnLegacyMapCommand.cs @@ -34,7 +34,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands { if (format > 1) { - Console.WriteLine("ERROR: Detected NewINIFormat {0}. Are you trying to import a Red Alert map?".F(format)); + Console.WriteLine($"ERROR: Detected NewINIFormat {format}. Are you trying to import a Red Alert map?"); return; } } diff --git a/OpenRA.Mods.Cnc/UtilityCommands/LegacyTilesetImporter.cs b/OpenRA.Mods.Cnc/UtilityCommands/LegacyTilesetImporter.cs index cb2fec03c7..3487aa1aae 100644 --- a/OpenRA.Mods.Cnc/UtilityCommands/LegacyTilesetImporter.cs +++ b/OpenRA.Mods.Cnc/UtilityCommands/LegacyTilesetImporter.cs @@ -63,8 +63,8 @@ namespace OpenRA.Mods.Cnc.UtilityCommands metadata.AppendLine("General:"); var name = args.Length > 3 ? args[3] : Path.GetFileNameWithoutExtension(args[2]); - metadata.AppendLine("\tName: {0}".F(name)); - metadata.AppendLine("\tId: {0}".F(name.ToUpperInvariant())); + metadata.AppendLine($"\tName: {name}"); + metadata.AppendLine($"\tId: {name.ToUpperInvariant()}"); metadata.AppendLine("\tHeightDebugColors: 00000080, 00004480, 00008880, 0000CC80, 0000FF80, 4400CC80," + " 88008880, CC004480, FF110080, FF550080, FF990080, FFDD0080, DDFF0080, 99FF0080, 55FF0080, 11FF0080"); @@ -77,7 +77,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands { for (var tilesetGroupIndex = 0; ; tilesetGroupIndex++) { - var section = file.GetSection("TileSet{0:D4}".F(tilesetGroupIndex)); + var section = file.GetSection($"TileSet{tilesetGroupIndex:D4}"); var sectionCount = int.Parse(section.GetValue("TilesInSet", "1")); var sectionFilename = section.GetValue("FileName", "").ToLowerInvariant(); @@ -88,29 +88,29 @@ namespace OpenRA.Mods.Cnc.UtilityCommands // Loop over templates for (var i = 1; i <= sectionCount; i++, templateIndex++) { - var templateFilename = "{0}{1:D2}.{2}".F(sectionFilename, i, extension); + var templateFilename = $"{sectionFilename}{i:D2}.{extension}"; if (!modData.DefaultFileSystem.Exists(templateFilename)) continue; using (var s = modData.DefaultFileSystem.Open(templateFilename)) { - data.AppendLine("\tTemplate@{0}:".F(templateIndex)); - data.AppendLine("\t\tCategories: {0}".F(sectionCategory)); + data.AppendLine($"\tTemplate@{templateIndex}:"); + data.AppendLine($"\t\tCategories: {sectionCategory}"); usedCategories.Add(sectionCategory); - data.AppendLine("\t\tId: {0}".F(templateIndex)); + data.AppendLine($"\t\tId: {templateIndex}"); var images = new List(); - images.Add("{0}{1:D2}.{2}".F(sectionFilename, i, extension)); + images.Add($"{sectionFilename}{i:D2}.{extension}"); for (var v = 'a'; v <= 'z'; v++) { - var variant = "{0}{1:D2}{2}.{3}".F(sectionFilename, i, v, extension); + var variant = $"{sectionFilename}{i:D2}{v}.{extension}"; if (modData.DefaultFileSystem.Exists(variant)) images.Add(variant); } - data.AppendLine("\t\tImages: {0}".F(images.JoinWith(", "))); + data.AppendLine($"\t\tImages: {images.JoinWith(", ")}"); var templateWidth = s.ReadUInt32(); var templateHeight = s.ReadUInt32(); @@ -120,7 +120,7 @@ namespace OpenRA.Mods.Cnc.UtilityCommands for (var j = 0; j < offsets.Length; j++) offsets[j] = s.ReadUInt32(); - data.AppendLine("\t\tSize: {0}, {1}".F(templateWidth, templateHeight)); + data.AppendLine($"\t\tSize: {templateWidth}, {templateHeight}"); data.AppendLine("\t\tTiles:"); for (var j = 0; j < offsets.Length; j++) @@ -134,18 +134,18 @@ namespace OpenRA.Mods.Cnc.UtilityCommands var rampType = s.ReadUInt8(); if (terrainType >= terrainTypes.Length) - throw new InvalidDataException("Unknown terrain type {0} in {1}".F(terrainType, templateFilename)); + throw new InvalidDataException($"Unknown terrain type {terrainType} in {templateFilename}"); - data.AppendLine("\t\t\t{0}: {1}".F(j, terrainTypes[terrainType])); + data.AppendLine($"\t\t\t{j}: {terrainTypes[terrainType]}"); if (height != 0) - data.AppendLine("\t\t\t\tHeight: {0}".F(height)); + data.AppendLine($"\t\t\t\tHeight: {height}"); if (rampType != 0) - data.AppendLine("\t\t\t\tRampType: {0}".F(rampType)); + data.AppendLine($"\t\t\t\tRampType: {rampType}"); - data.AppendLine("\t\t\t\tMinColor: {0:X2}{1:X2}{2:X2}".F(s.ReadUInt8(), s.ReadUInt8(), s.ReadUInt8())); - data.AppendLine("\t\t\t\tMaxColor: {0:X2}{1:X2}{2:X2}".F(s.ReadUInt8(), s.ReadUInt8(), s.ReadUInt8())); - data.AppendLine("\t\t\t\tZOffset: {0}".F(-tileSize.Height / 2.0f)); + data.AppendLine($"\t\t\t\tMinColor: {s.ReadUInt8():X2}{s.ReadUInt8():X2}{s.ReadUInt8():X2}"); + data.AppendLine($"\t\t\t\tMaxColor: {s.ReadUInt8():X2}{s.ReadUInt8():X2}{s.ReadUInt8():X2}"); + data.AppendLine($"\t\t\t\tZOffset: {(-tileSize.Height / 2.0f)}"); data.AppendLine("\t\t\t\tZRamp: 0"); } } @@ -169,8 +169,8 @@ namespace OpenRA.Mods.Cnc.UtilityCommands terrainTypes = terrainTypes.Distinct().ToArray(); foreach (var terrainType in terrainTypes) { - metadata.AppendLine("\tTerrainType@{0}:".F(terrainType)); - metadata.AppendLine("\t\tType: {0}".F(terrainType)); + metadata.AppendLine($"\tTerrainType@{terrainType}:"); + metadata.AppendLine($"\t\tType: {terrainType}"); if (terrainType == "Water") metadata.AppendLine("\t\tTargetTypes: Water"); diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs index 5fa06d4ebf..8a4fdf9882 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorActorBrush.cs @@ -102,7 +102,7 @@ namespace OpenRA.Mods.Common.Widgets public void Do() { editorActorPreview = editorLayer.Add(actor); - Text = "Added {0} ({1})".F(editorActorPreview.Info.Name, editorActorPreview.ID); + Text = $"Added {editorActorPreview.Info.Name} ({editorActorPreview.ID})"; } public void Undo() diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs index 9bb18de6a6..725905a173 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorCopyPasteBrush.cs @@ -204,7 +204,7 @@ namespace OpenRA.Mods.Common.Widgets mapHeight = map.Height; mapResources = map.Resources; - Text = "Copied {0} tiles".F(tiles.Count); + Text = $"Copied {tiles.Count} tiles"; } public void Execute() diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorDefaultBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorDefaultBrush.cs index 2b6c48be34..9af645afd0 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorDefaultBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorDefaultBrush.cs @@ -122,7 +122,7 @@ namespace OpenRA.Mods.Common.Widgets this.editorActorLayer = editorActorLayer; this.actor = actor; - Text = "Removed {0} ({1})".F(actor.Info.Name, actor.ID); + Text = $"Removed {actor.Info.Name} ({actor.ID})"; } public void Execute() @@ -155,7 +155,7 @@ namespace OpenRA.Mods.Common.Widgets this.resourceLayer = resourceLayer; this.cell = cell; - Text = "Removed {0}".F(resourceType); + Text = $"Removed {resourceType}"; } public void Execute() diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorResourceBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorResourceBrush.cs index 7b48608b9e..0d8e673154 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorResourceBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorResourceBrush.cs @@ -149,7 +149,7 @@ namespace OpenRA.Mods.Common.Widgets cellResources.Add(resourceCell); var cellText = cellResources.Count != 1 ? "cells" : "cell"; - Text = "Added {0} {1} of {2}".F(cellResources.Count, cellText, resourceType); + Text = $"Added {cellResources.Count} {cellText} of {resourceType}"; } } } diff --git a/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs b/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs index babf4e3cc6..29b191ba39 100644 --- a/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs +++ b/OpenRA.Mods.Common/EditorBrushes/EditorTileBrush.cs @@ -170,7 +170,7 @@ namespace OpenRA.Mods.Common.Widgets var terrainInfo = (ITemplatedTerrainInfo)map.Rules.TerrainInfo; terrainTemplate = terrainInfo.Templates[template]; - Text = "Added tile {0}".F(terrainTemplate.Id); + Text = $"Added tile {terrainTemplate.Id}"; } public void Execute() @@ -239,7 +239,7 @@ namespace OpenRA.Mods.Common.Widgets var terrainInfo = (ITemplatedTerrainInfo)map.Rules.TerrainInfo; terrainTemplate = terrainInfo.Templates[template]; - Text = "Filled with tile {0}".F(terrainTemplate.Id); + Text = $"Filled with tile {terrainTemplate.Id}"; } public void Execute() diff --git a/OpenRA.Mods.Common/Effects/FloatingText.cs b/OpenRA.Mods.Common/Effects/FloatingText.cs index 93db5a452d..e6b7dc7ec6 100644 --- a/OpenRA.Mods.Common/Effects/FloatingText.cs +++ b/OpenRA.Mods.Common/Effects/FloatingText.cs @@ -57,7 +57,7 @@ namespace OpenRA.Mods.Common.Effects public static string FormatCashTick(int cashAmount) { - return "{0}${1}".F(cashAmount < 0 ? "-" : "+", Math.Abs(cashAmount)); + return $"{(cashAmount < 0 ? "-" : "+")}${Math.Abs(cashAmount)}"; } } } diff --git a/OpenRA.Mods.Common/FileFormats/InstallShieldCABCompression.cs b/OpenRA.Mods.Common/FileFormats/InstallShieldCABCompression.cs index 329f4ec18b..580ef95fd9 100644 --- a/OpenRA.Mods.Common/FileFormats/InstallShieldCABCompression.cs +++ b/OpenRA.Mods.Common/FileFormats/InstallShieldCABCompression.cs @@ -292,7 +292,7 @@ namespace OpenRA.Mods.Common.FileFormats { currentVolumeID = newVolume; if (!volumes.TryGetValue(currentVolumeID, out currentVolume)) - throw new FileNotFoundException("Volume {0} is not available".F(currentVolumeID)); + throw new FileNotFoundException($"Volume {currentVolumeID} is not available"); currentVolume.Position = 0; if (currentVolume.ReadUInt32() != 0x28635349) @@ -385,7 +385,7 @@ namespace OpenRA.Mods.Common.FileFormats { header.Position = cabDescriptorOffset + cabDescriptor.FileTableOffset + cabDescriptor.FileTableOffset2 + i * 0x57; var file = new FileDescriptor(header, i, cabDescriptorOffset + cabDescriptor.FileTableOffset); - var path = "{0}\\{1}\\{2}".F(fileGroup.Name, directories[file.DirectoryIndex].Name, file.Filename); + var path = $"{fileGroup.Name}\\{directories[file.DirectoryIndex].Name}\\{file.Filename}"; index[path] = file; } } @@ -418,7 +418,7 @@ namespace OpenRA.Mods.Common.FileFormats extracter.CopyTo(output, onProgress); if (output.Length != file.ExpandedSize) - throw new InvalidDataException("File expanded to wrong length. Expected = {0}, Got = {1}".F(file.ExpandedSize, output.Length)); + throw new InvalidDataException($"File expanded to wrong length. Expected = {file.ExpandedSize}, Got = {output.Length}"); } public IReadOnlyDictionary> Contents diff --git a/OpenRA.Mods.Common/FileFormats/WavReader.cs b/OpenRA.Mods.Common/FileFormats/WavReader.cs index 6bebb15f89..412904740a 100644 --- a/OpenRA.Mods.Common/FileFormats/WavReader.cs +++ b/OpenRA.Mods.Common/FileFormats/WavReader.cs @@ -58,7 +58,7 @@ namespace OpenRA.Mods.Common.FileFormats audioType = (WaveType)audioFormat; if (!Enum.IsDefined(typeof(WaveType), audioType)) - throw new NotSupportedException("Compression type {0} is not supported.".F(audioFormat)); + throw new NotSupportedException($"Compression type {audioFormat} is not supported."); channels = s.ReadInt16(); sampleRate = s.ReadInt32(); diff --git a/OpenRA.Mods.Common/Graphics/DefaultSpriteSequence.cs b/OpenRA.Mods.Common/Graphics/DefaultSpriteSequence.cs index 6a4a20b715..0bd81e7d82 100644 --- a/OpenRA.Mods.Common/Graphics/DefaultSpriteSequence.cs +++ b/OpenRA.Mods.Common/Graphics/DefaultSpriteSequence.cs @@ -67,12 +67,12 @@ namespace OpenRA.Mods.Common.Graphics } catch (Exception e) { - throw new InvalidDataException("Error occurred while parsing {0}".F(node.Key), e); + throw new InvalidDataException($"Error occurred while parsing {node.Key}", e); } foreach (var kvp in nodes) { - using (new Support.PerfTimer("new Sequence(\"{0}\")".F(node.Key), 20)) + using (new Support.PerfTimer($"new Sequence(\"{node.Key}\")", 20)) { try { @@ -223,32 +223,26 @@ namespace OpenRA.Mods.Common.Graphics Stride = LoadField(d, "Stride", Length); if (Length > Stride) - throw new YamlException("Sequence {0}.{1}: Length must be <= stride" - .F(sequence, animation)); + throw new YamlException($"Sequence {sequence}.{animation}: Length must be <= stride"); if (Frames != null && Length > Frames.Length) - throw new YamlException("Sequence {0}.{1}: Length must be <= Frames.Length" - .F(sequence, animation)); + throw new YamlException($"Sequence {sequence}.{animation}: Length must be <= Frames.Length"); var end = Start + (Facings - 1) * Stride + Length - 1; if (Frames != null) { foreach (var f in Frames) if (f < 0 || f >= frameCount) - throw new YamlException("Sequence {0}.{1} defines a Frames override that references frame {2}, but only [{3}..{4}] actually exist" - .F(sequence, animation, f, Start, end)); + throw new YamlException($"Sequence {sequence}.{animation} defines a Frames override that references frame {f}, but only [{Start}..{end}] actually exist"); if (Start < 0 || end >= Frames.Length) - throw new YamlException("Sequence {0}.{1} uses indices [{2}..{3}] of the Frames list, but only {4} frames are defined" - .F(sequence, animation, Start, end, Frames.Length)); + throw new YamlException($"Sequence {sequence}.{animation} uses indices [{Start}..{end}] of the Frames list, but only {Frames.Length} frames are defined"); } else if (Start < 0 || end >= frameCount) - throw new YamlException("Sequence {0}.{1} uses frames [{2}..{3}], but only [0..{4}] actually exist" - .F(sequence, animation, Start, end, frameCount - 1)); + throw new YamlException($"Sequence {sequence}.{animation} uses frames [{Start}..{end}], but only [0..{frameCount - 1}] actually exist"); if (ShadowStart >= 0 && ShadowStart + (Facings - 1) * Stride + Length > frameCount) - throw new YamlException("Sequence {0}.{1}'s shadow frames use frames [{2}..{3}], but only [0..{4}] actually exist" - .F(sequence, animation, ShadowStart, ShadowStart + (Facings - 1) * Stride + Length - 1, frameCount - 1)); + throw new YamlException($"Sequence {sequence}.{animation}'s shadow frames use frames [{ShadowStart}..{ShadowStart + (Facings - 1) * Stride + Length - 1}], but only [0..{frameCount - 1}] actually exist"); var usedFrames = new List(); for (var facing = 0; facing < Facings; facing++) @@ -325,13 +319,13 @@ namespace OpenRA.Mods.Common.Graphics if (alpha.Length == 1) alpha = Exts.MakeArray(Length, _ => alpha[0]); else if (alpha.Length != Length) - throw new YamlException("Sequence {0}.{1} must define either 1 or {2} Alpha values.".F(sequence, animation, Length)); + throw new YamlException($"Sequence {sequence}.{animation} must define either 1 or {Length} Alpha values."); } if (LoadField(d, "AlphaFade", false)) { if (alpha != null) - throw new YamlException("Sequence {0}.{1} cannot define both AlphaFade and Alpha.".F(sequence, animation)); + throw new YamlException($"Sequence {sequence}.{animation} cannot define both AlphaFade and Alpha."); alpha = Exts.MakeArray(Length, i => float2.Lerp(1f, 0f, i / (Length - 1f))); } @@ -368,7 +362,7 @@ namespace OpenRA.Mods.Common.Graphics var i = Frames != null ? Frames[0] : Start; var palettes = metadata != null ? metadata.GetOrDefault() : null; if (palettes == null || !palettes.TryGetPaletteForFrame(i, out EmbeddedPalette)) - throw new YamlException("Cannot export palettes from {0}: frame {1} does not define an embedded palette".F(src, i)); + throw new YamlException($"Cannot export palettes from {src}: frame {i} does not define an embedded palette"); } var boundSprites = SpriteBounds(sprites, Frames, Start, Facings, Length, Stride, transpose); @@ -379,7 +373,7 @@ namespace OpenRA.Mods.Common.Graphics } catch (FormatException f) { - throw new FormatException("Failed to parse sequences for {0}.{1} at {2}:\n{3}".F(sequence, animation, info.Nodes[0].Location, f)); + throw new FormatException($"Failed to parse sequences for {sequence}.{animation} at {info.Nodes[0].Location}:\n{f}"); } } @@ -428,8 +422,7 @@ namespace OpenRA.Mods.Common.Graphics var j = Frames != null ? Frames[i] : start + i; if (sprites[j] == null) - throw new InvalidOperationException("Attempted to query unloaded sprite from {0}.{1}".F(Name, sequence) + - " start={0} frame={1} facing={2}".F(start, frame, facing)); + throw new InvalidOperationException($"Attempted to query unloaded sprite from {Name}.{sequence} start={start} frame={frame} facing={facing}"); return sprites[j]; } diff --git a/OpenRA.Mods.Common/Lint/CheckActorReferences.cs b/OpenRA.Mods.Common/Lint/CheckActorReferences.cs index 1380fcc632..3f605f515f 100644 --- a/OpenRA.Mods.Common/Lint/CheckActorReferences.cs +++ b/OpenRA.Mods.Common/Lint/CheckActorReferences.cs @@ -68,16 +68,14 @@ namespace OpenRA.Mods.Common.Lint if (!dict.ContainsKey(v)) { - emitError("{0}.{1}.{2}: Missing actor `{3}`." - .F(actorInfo.Name, traitInfo.GetType().Name, fieldInfo.Name, value)); + emitError($"{actorInfo.Name}.{traitInfo.GetType().Name}.{fieldInfo.Name}: Missing actor `{value}`."); continue; } foreach (var requiredTrait in attribute.RequiredTraits) if (!dict[v].TraitsInConstructOrder().Any(t => t.GetType() == requiredTrait || t.GetType().IsSubclassOf(requiredTrait))) - emitError("Actor type {0} does not have trait {1} which is required by {2}.{3}." - .F(value, requiredTrait.Name, traitInfo.GetType().Name, fieldInfo.Name)); + emitError($"Actor type {value} does not have trait {requiredTrait.Name} which is required by {traitInfo.GetType().Name}.{fieldInfo.Name}."); } } @@ -91,8 +89,7 @@ namespace OpenRA.Mods.Common.Lint continue; if (!dict.ContainsKey(value.ToLowerInvariant())) - emitError("{0}.{1}.{2}: Missing weapon `{3}`." - .F(actorInfo.Name, traitInfo.GetType().Name, fieldInfo.Name, value)); + emitError($"{actorInfo.Name}.{traitInfo.GetType().Name}.{fieldInfo.Name}: Missing weapon `{value}`."); } } @@ -106,8 +103,7 @@ namespace OpenRA.Mods.Common.Lint continue; if (!dict.ContainsKey(value.ToLowerInvariant())) - emitError("{0}.{1}.{2}: Missing voice `{3}`." - .F(actorInfo.Name, traitInfo.GetType().Name, fieldInfo.Name, value)); + emitError($"{actorInfo.Name}.{traitInfo.GetType().Name}.{fieldInfo.Name}: Missing voice `{value}`."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckActors.cs b/OpenRA.Mods.Common/Lint/CheckActors.cs index d0b91f91b4..7a7c5fe2b6 100644 --- a/OpenRA.Mods.Common/Lint/CheckActors.cs +++ b/OpenRA.Mods.Common/Lint/CheckActors.cs @@ -21,7 +21,7 @@ namespace OpenRA.Mods.Common.Lint var actorTypes = map.ActorDefinitions.Select(a => a.Value.Value); foreach (var actor in actorTypes) if (!map.Rules.Actors.Keys.Contains(actor.ToLowerInvariant())) - emitError("Actor {0} is not defined by any rule.".F(actor)); + emitError($"Actor {actor} is not defined by any rule."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckAngle.cs b/OpenRA.Mods.Common/Lint/CheckAngle.cs index ec6a68a84e..c957f2e153 100644 --- a/OpenRA.Mods.Common/Lint/CheckAngle.cs +++ b/OpenRA.Mods.Common/Lint/CheckAngle.cs @@ -61,16 +61,16 @@ namespace OpenRA.Mods.Common.Lint static void CheckLaunchAngles(string weaponInfo, int minAngle, bool testMaxAngle, int maxAngle, Action emitError) { if (InvalidAngle(minAngle)) - emitError("Weapon `{0}`: Projectile minimum LaunchAngle must not exceed (-)255!".F(weaponInfo)); + emitError($"Weapon `{weaponInfo}`: Projectile minimum LaunchAngle must not exceed (-)255!"); if (testMaxAngle && InvalidAngle(maxAngle)) - emitError("Weapon `{0}`: Projectile maximum LaunchAngle must not exceed (-)255!".F(weaponInfo)); + emitError($"Weapon `{weaponInfo}`: Projectile maximum LaunchAngle must not exceed (-)255!"); if ((minAngle < 256) && (maxAngle < 256) && (minAngle > maxAngle)) - emitError("Weapon `{0}`: Projectile minimum LaunchAngle must not exceed maximum LaunchAngle!".F(weaponInfo)); + emitError($"Weapon `{weaponInfo}`: Projectile minimum LaunchAngle must not exceed maximum LaunchAngle!"); if ((minAngle > 768) && (maxAngle > 768) && (minAngle > maxAngle)) - emitError("Weapon `{0}`: Projectile minimum LaunchAngle must not exceed maximum LaunchAngle!".F(weaponInfo)); + emitError($"Weapon `{weaponInfo}`: Projectile minimum LaunchAngle must not exceed maximum LaunchAngle!"); if ((minAngle < 256) && (maxAngle > 768)) - emitError("Weapon `{0}`: Projectile minimum LaunchAngle must not exceed maximum LaunchAngle!".F(weaponInfo)); + emitError($"Weapon `{weaponInfo}`: Projectile minimum LaunchAngle must not exceed maximum LaunchAngle!"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckChromeHotkeys.cs b/OpenRA.Mods.Common/Lint/CheckChromeHotkeys.cs index e6d91197e1..f50f8dd03d 100644 --- a/OpenRA.Mods.Common/Lint/CheckChromeHotkeys.cs +++ b/OpenRA.Mods.Common/Lint/CheckChromeHotkeys.cs @@ -78,7 +78,7 @@ namespace OpenRA.Mods.Common.Lint { // Keys are valid if they refer to a named key or can be parsed as a regular Hotkey. if (!namedKeys.Contains(node.Value.Value) && !Hotkey.TryParse(node.Value.Value, out var unused)) - emitError("{0} refers to a Key named `{1}` that does not exist".F(node.Location, node.Value.Value)); + emitError($"{node.Location} refers to a Key named `{node.Value.Value}` that does not exist"); } } @@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Lint foreach (var name in keyNames) if (!namedKeys.Contains(name) && !Hotkey.TryParse(name, out var unused)) - emitError("{0} refers to a Key named `{1}` that does not exist".F(node.Location, name)); + emitError($"{node.Location} refers to a Key named `{name}` that does not exist"); } // Logic classes can declare the data key names that specify hotkeys @@ -111,7 +111,7 @@ namespace OpenRA.Mods.Common.Lint foreach (var n in node.Value.Nodes) if (checkArgKeys.Contains(n.Key)) if (!namedKeys.Contains(n.Value.Value) && !Hotkey.TryParse(n.Value.Value, out var unused)) - emitError("{0} {1}:{2} refers to a Key named `{3}` that does not exist".F(filename, node.Value.Value, n.Key, n.Value.Value)); + emitError($"{filename} {node.Value.Value}:{n.Key} refers to a Key named `{n.Value.Value}` that does not exist"); } if (node.Value.Nodes != null) diff --git a/OpenRA.Mods.Common/Lint/CheckChromeLogic.cs b/OpenRA.Mods.Common/Lint/CheckChromeLogic.cs index 3f4ba11242..4c73f11296 100644 --- a/OpenRA.Mods.Common/Lint/CheckChromeLogic.cs +++ b/OpenRA.Mods.Common/Lint/CheckChromeLogic.cs @@ -37,9 +37,9 @@ namespace OpenRA.Mods.Common.Lint { var type = Game.ModData.ObjectCreator.FindType(typeName); if (type == null) - emitError("{0} refers to a logic object `{1}` that does not exist".F(filename, typeName)); + emitError($"{filename} refers to a logic object `{typeName}` that does not exist"); else if (!typeof(ChromeLogic).IsAssignableFrom(type)) - emitError("{0} refers to a logic object `{1}` that does not inherit from ChromeLogic".F(filename, typeName)); + emitError($"{filename} refers to a logic object `{typeName}` that does not inherit from ChromeLogic"); } } diff --git a/OpenRA.Mods.Common/Lint/CheckConditions.cs b/OpenRA.Mods.Common/Lint/CheckConditions.cs index 2ef7ef9e69..5a80b93ad8 100644 --- a/OpenRA.Mods.Common/Lint/CheckConditions.cs +++ b/OpenRA.Mods.Common/Lint/CheckConditions.cs @@ -65,11 +65,11 @@ namespace OpenRA.Mods.Common.Lint var unconsumed = granted.Except(consumed); if (unconsumed.Any()) - emitWarning("Actor type `{0}` grants conditions that are not consumed: {1}".F(actorInfo.Key, unconsumed.JoinWith(", "))); + emitWarning($"Actor type `{actorInfo.Key}` grants conditions that are not consumed: {unconsumed.JoinWith(", ")}"); var ungranted = consumed.Except(granted); if (ungranted.Any()) - emitError("Actor type `{0}` consumes conditions that are not granted: {1}".F(actorInfo.Key, ungranted.JoinWith(", "))); + emitError($"Actor type `{actorInfo.Key}` consumes conditions that are not granted: {ungranted.JoinWith(", ")}"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckConflictingMouseBounds.cs b/OpenRA.Mods.Common/Lint/CheckConflictingMouseBounds.cs index 77d1b47848..02f131f7ba 100644 --- a/OpenRA.Mods.Common/Lint/CheckConflictingMouseBounds.cs +++ b/OpenRA.Mods.Common/Lint/CheckConflictingMouseBounds.cs @@ -25,7 +25,7 @@ namespace OpenRA.Mods.Common.Lint var selectable = actorInfo.Value.TraitInfos().Count(); var interactable = actorInfo.Value.TraitInfos().Count(); if (selectable > 0 && selectable != interactable) - emitWarning("Actor {0} defines both Interactable and Selectable traits. This may cause unexpected results.".F(actorInfo.Value.Name)); + emitWarning($"Actor {actorInfo.Value.Name} defines both Interactable and Selectable traits. This may cause unexpected results."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckCursors.cs b/OpenRA.Mods.Common/Lint/CheckCursors.cs index 8343e9e918..5bcea70d6a 100644 --- a/OpenRA.Mods.Common/Lint/CheckCursors.cs +++ b/OpenRA.Mods.Common/Lint/CheckCursors.cs @@ -57,7 +57,7 @@ namespace OpenRA.Mods.Common.Lint continue; if (!cursors.Contains(cursor)) - emitError("Undefined cursor {0} for actor {1} with trait {2}.".F(cursor, actorInfo.Value.Name, traitInfo)); + emitError($"Undefined cursor {cursor} for actor {actorInfo.Value.Name} with trait {traitInfo}."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckDefaultVisibility.cs b/OpenRA.Mods.Common/Lint/CheckDefaultVisibility.cs index fdca436355..6dd1061a8e 100644 --- a/OpenRA.Mods.Common/Lint/CheckDefaultVisibility.cs +++ b/OpenRA.Mods.Common/Lint/CheckDefaultVisibility.cs @@ -36,9 +36,9 @@ namespace OpenRA.Mods.Common.Lint var count = actorInfo.Value.TraitInfos().Count(); if (count == 0) - emitError("Actor type `{0}` does not define a default visibility type!".F(actorInfo.Key)); + emitError($"Actor type `{actorInfo.Key}` does not define a default visibility type!"); else if (count > 1) - emitError("Actor type `{0}` defines multiple default visibility types!".F(actorInfo.Key)); + emitError($"Actor type `{actorInfo.Key}` defines multiple default visibility types!"); else { var vis = actorInfo.Value.TraitInfoOrDefault(); @@ -46,9 +46,9 @@ namespace OpenRA.Mods.Common.Lint { var ios = actorInfo.Value.TraitInfoOrDefault(); if (ios == null) - emitError("Actor type `{0}` defines VisibilityType.Footprint in `{1}` but has no IOccupySpace traits!".F(actorInfo.Key, vis.GetType())); + emitError($"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{vis.GetType()}` but has no IOccupySpace traits!"); else if (!ios.OccupiedCells(actorInfo.Value, CPos.Zero).Any()) - emitError("Actor type `{0}` defines VisibilityType.Footprint in `{1}` but does not have any footprint cells!".F(actorInfo.Key, vis.GetType())); + emitError($"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{vis.GetType()}` but does not have any footprint cells!"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckHitShapes.cs b/OpenRA.Mods.Common/Lint/CheckHitShapes.cs index e308ec1d66..2011243ced 100644 --- a/OpenRA.Mods.Common/Lint/CheckHitShapes.cs +++ b/OpenRA.Mods.Common/Lint/CheckHitShapes.cs @@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Lint var hitShapes = actorInfo.Value.TraitInfos(); if (!hitShapes.Any()) - emitError("Actor type `{0}` has a Health trait but no HitShape trait!".F(actorInfo.Key)); + emitError($"Actor type `{actorInfo.Key}` has a Health trait but no HitShape trait!"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckLocomotorReferences.cs b/OpenRA.Mods.Common/Lint/CheckLocomotorReferences.cs index 1e3f7abc05..cd3f3c7935 100644 --- a/OpenRA.Mods.Common/Lint/CheckLocomotorReferences.cs +++ b/OpenRA.Mods.Common/Lint/CheckLocomotorReferences.cs @@ -36,7 +36,7 @@ namespace OpenRA.Mods.Common.Lint foreach (var li in locomotorInfos) foreach (var otherLocomotor in locomotorInfos) if (li != otherLocomotor && li.Name == otherLocomotor.Name) - emitError("There is more than one Locomotor with name {0}!".F(li.Name)); + emitError($"There is more than one Locomotor with name {li.Name}!"); foreach (var actorInfo in rules.Actors) { @@ -61,7 +61,7 @@ namespace OpenRA.Mods.Common.Lint void CheckLocomotors(ActorInfo actorInfo, Action emitError, Ruleset rules, LocomotorInfo[] locomotorInfos, string locomotor) { if (!locomotorInfos.Any(l => l.Name == locomotor)) - emitError("Actor {0} defines Locomotor {1} not found on World actor.".F(actorInfo.Name, locomotor)); + emitError($"Actor {actorInfo.Name} defines Locomotor {locomotor} not found on World actor."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs b/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs index 56f169f208..27877a984c 100644 --- a/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs +++ b/OpenRA.Mods.Common/Lint/CheckMapMetadata.cs @@ -30,7 +30,7 @@ namespace OpenRA.Mods.Common.Lint void Run(Action emitError, int mapFormat, string author, string title, string[] categories) { if (mapFormat != Map.SupportedMapFormat) - emitError("Map format {0} does not match the supported version {1}.".F(mapFormat, Map.SupportedMapFormat)); + emitError($"Map format {mapFormat} does not match the supported version {Map.SupportedMapFormat}."); if (author == null) emitError("Map does not define a valid author."); diff --git a/OpenRA.Mods.Common/Lint/CheckMapTiles.cs b/OpenRA.Mods.Common/Lint/CheckMapTiles.cs index df13b31604..563de9ea8b 100644 --- a/OpenRA.Mods.Common/Lint/CheckMapTiles.cs +++ b/OpenRA.Mods.Common/Lint/CheckMapTiles.cs @@ -19,7 +19,7 @@ namespace OpenRA.Mods.Common.Lint public void Run(Action emitError, Action emitWarning, ModData modData, Map map) { foreach (var kv in map.ReplacedInvalidTerrainTiles) - emitError("Cell {0} references invalid terrain tile {1}.".F(kv.Key, kv.Value)); + emitError($"Cell {kv.Key} references invalid terrain tile {kv.Value}."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckNotifications.cs b/OpenRA.Mods.Common/Lint/CheckNotifications.cs index fa7490da9a..59f99684fb 100644 --- a/OpenRA.Mods.Common/Lint/CheckNotifications.cs +++ b/OpenRA.Mods.Common/Lint/CheckNotifications.cs @@ -56,8 +56,7 @@ namespace OpenRA.Mods.Common.Lint if (string.IsNullOrEmpty(type) || !rules.Notifications.TryGetValue(type.ToLowerInvariant(), out var soundInfo) || !soundInfo.Notifications.ContainsKey(notification)) - emitError("Undefined notification reference {0}.{1} detected at {2} for {3}".F( - type ?? "(null)", notification, traitInfo.GetType().Name, actorInfo.Key)); + emitError($"Undefined notification reference {type ?? "(null)"}.{notification} detected at {traitInfo.GetType().Name} for {actorInfo.Key}"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckOwners.cs b/OpenRA.Mods.Common/Lint/CheckOwners.cs index 053868a846..016f38629c 100644 --- a/OpenRA.Mods.Common/Lint/CheckOwners.cs +++ b/OpenRA.Mods.Common/Lint/CheckOwners.cs @@ -35,16 +35,16 @@ namespace OpenRA.Mods.Common.Lint var actorReference = new ActorReference(kv.Value.Value, kv.Value.ToDictionary()); var ownerInit = actorReference.GetOrDefault(); if (ownerInit == null) - emitError("Actor {0} is not owned by any player.".F(kv.Key)); + emitError($"Actor {kv.Key} is not owned by any player."); else { var ownerName = ownerInit.InternalName; if (!playerNames.Contains(ownerName)) - emitError("Actor {0} is owned by unknown player {1}.".F(kv.Key, ownerName)); + emitError($"Actor {kv.Key} is owned by unknown player {ownerName}."); if (actorsWithRequiredOwner.TryGetValue(kv.Value.Value, out var info)) if (!info.ValidOwnerNames.Contains(ownerName)) - emitError("Actor {0} owner {1} is not one of ValidOwnerNames: {2}".F(kv.Key, ownerName, info.ValidOwnerNames.JoinWith(", "))); + emitError($"Actor {kv.Key} owner {ownerName} is not one of ValidOwnerNames: {info.ValidOwnerNames.JoinWith(", ")}"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckPalettes.cs b/OpenRA.Mods.Common/Lint/CheckPalettes.cs index 128d1372de..e7be536471 100644 --- a/OpenRA.Mods.Common/Lint/CheckPalettes.cs +++ b/OpenRA.Mods.Common/Lint/CheckPalettes.cs @@ -65,12 +65,12 @@ namespace OpenRA.Mods.Common.Lint if (isPlayerPalette) { if (!playerPalettes.Contains(reference)) - emitError("Undefined player palette reference {0} detected at {1} for {2}".F(reference, traitInfo, actorInfo.Key)); + emitError($"Undefined player palette reference {reference} detected at {traitInfo} for {actorInfo.Key}"); } else { if (!palettes.Contains(reference)) - emitError("Undefined palette reference {0} detected at {1} for {2}".F(reference, traitInfo, actorInfo.Key)); + emitError($"Undefined palette reference {reference} detected at {traitInfo} for {actorInfo.Key}"); } } } @@ -109,12 +109,12 @@ namespace OpenRA.Mods.Common.Lint if (isPlayerPalette) { if (!playerPalettes.Contains(reference)) - emitError("Undefined player palette reference {0} detected at weapon {1}.".F(reference, weaponInfo.Key)); + emitError($"Undefined player palette reference {reference} detected at weapon {weaponInfo.Key}."); } else { if (!palettes.Contains(reference)) - emitError("Undefined palette reference {0} detected at weapon {1}.".F(reference, weaponInfo.Key)); + emitError($"Undefined palette reference {reference} detected at weapon {weaponInfo.Key}."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckPlayers.cs b/OpenRA.Mods.Common/Lint/CheckPlayers.cs index 710f2248ec..bd413c4319 100644 --- a/OpenRA.Mods.Common/Lint/CheckPlayers.cs +++ b/OpenRA.Mods.Common/Lint/CheckPlayers.cs @@ -49,25 +49,25 @@ namespace OpenRA.Mods.Common.Lint { foreach (var ally in player.Allies) if (!playerNames.Contains(ally)) - emitError("Allies contains player {0} that is not in list.".F(ally)); + emitError($"Allies contains player {ally} that is not in list."); foreach (var enemy in player.Enemies) if (!playerNames.Contains(enemy)) - emitError("Enemies contains player {0} that is not in list.".F(enemy)); + emitError($"Enemies contains player {enemy} that is not in list."); if (player.OwnsWorld) { worldOwnerFound = true; if (player.Enemies.Any() || player.Allies.Any()) - emitWarning("The player {0} owning the world should not have any allies or enemies.".F(player.Name)); + emitWarning($"The player {player.Name} owning the world should not have any allies or enemies."); if (player.Playable) - emitError("The player {0} owning the world can't be playable.".F(player.Name)); + emitError($"The player {player.Name} owning the world can't be playable."); } else if (visibility == MapVisibility.MissionSelector && player.Playable && !player.LockFaction) { // Missions must lock the faction of the player to force the server to override the default Random faction - emitError("The player {0} must specify LockFaction: True.".F(player.Name)); + emitError($"The player {player.Name} must specify LockFaction: True."); } } @@ -77,13 +77,13 @@ namespace OpenRA.Mods.Common.Lint var factions = worldActorInfo.TraitInfos().Select(f => f.InternalName).ToHashSet(); foreach (var player in players.Players.Values) if (!string.IsNullOrWhiteSpace(player.Faction) && !factions.Contains(player.Faction)) - emitError("Invalid faction {0} chosen for player {1}.".F(player.Faction, player.Name)); + emitError($"Invalid faction {player.Faction} chosen for player {player.Name}."); if (worldActorInfo.HasTraitInfo()) { var playerCount = players.Players.Count(p => p.Value.Playable); if (playerCount > spawnPoints.Length) - emitError("The map allows {0} possible players, but defines only {1} spawn points".F(playerCount, spawnPoints.Length)); + emitError($"The map allows {playerCount} possible players, but defines only {spawnPoints.Length} spawn points"); if (spawnPoints.Distinct().Count() != spawnPoints.Length) emitError("Duplicate spawn point locations detected."); diff --git a/OpenRA.Mods.Common/Lint/CheckRangeLimit.cs b/OpenRA.Mods.Common/Lint/CheckRangeLimit.cs index a5cc5ba4b9..9326c11d18 100644 --- a/OpenRA.Mods.Common/Lint/CheckRangeLimit.cs +++ b/OpenRA.Mods.Common/Lint/CheckRangeLimit.cs @@ -34,8 +34,7 @@ namespace OpenRA.Mods.Common.Lint var range = weaponInfo.Value.Range; if (weaponInfo.Value.Projectile is MissileInfo missile && missile.RangeLimit > WDist.Zero && missile.RangeLimit < range) - emitError("Weapon `{0}`: projectile RangeLimit lower than weapon range!" - .F(weaponInfo.Key)); + emitError($"Weapon `{weaponInfo.Key}`: projectile RangeLimit lower than weapon range!"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckRevealFootprint.cs b/OpenRA.Mods.Common/Lint/CheckRevealFootprint.cs index d0726437fb..e8a3b90577 100644 --- a/OpenRA.Mods.Common/Lint/CheckRevealFootprint.cs +++ b/OpenRA.Mods.Common/Lint/CheckRevealFootprint.cs @@ -40,9 +40,9 @@ namespace OpenRA.Mods.Common.Lint continue; if (ios == null) - emitError("Actor type `{0}` defines VisibilityType.Footprint in `{1}` but has no IOccupySpace traits!".F(actorInfo.Key, rsi.GetType())); + emitError($"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{rsi.GetType()}` but has no IOccupySpace traits!"); else if (!ios.OccupiedCells(actorInfo.Value, CPos.Zero).Any()) - emitError("Actor type `{0}` defines VisibilityType.Footprint in `{1}` but does not have any footprint cells!".F(actorInfo.Key, rsi.GetType())); + emitError($"Actor type `{actorInfo.Key}` defines VisibilityType.Footprint in `{rsi.GetType()}` but does not have any footprint cells!"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckSequences.cs b/OpenRA.Mods.Common/Lint/CheckSequences.cs index 6185199994..a7f12d2c82 100644 --- a/OpenRA.Mods.Common/Lint/CheckSequences.cs +++ b/OpenRA.Mods.Common/Lint/CheckSequences.cs @@ -77,7 +77,7 @@ namespace OpenRA.Mods.Common.Lint if (string.IsNullOrEmpty(imageOverride)) { if (!sequenceReference.AllowNullImage) - emitError("Actor type `{0}` trait `{1}` must define a value for `{2}`".F(actorInfo.Value.Name, traitName, sequenceReference.ImageReference)); + emitError($"Actor type `{actorInfo.Value.Name}` trait `{traitName}` must define a value for `{sequenceReference.ImageReference}`"); continue; } @@ -95,10 +95,10 @@ namespace OpenRA.Mods.Common.Lint { // TODO: Remove prefixed sequence references and instead use explicit lists of lintable references if (!sequences.Sequences(i).Any(s => s.StartsWith(sequence))) - emitWarning("Actor type `{0}` trait `{1}` field `{2}` defines a prefix `{3}` that does not match any sequences on image `{4}`.".F(actorInfo.Value.Name, traitName, field.Name, sequence, i)); + emitWarning($"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` defines a prefix `{sequence}` that does not match any sequences on image `{i}`."); } else if (!sequences.HasSequence(i, sequence)) - emitError("Actor type `{0}` trait `{1}` field `{2}` references an undefined sequence `{3}` on image `{4}`.".F(actorInfo.Value.Name, traitName, field.Name, sequence, i)); + emitError($"Actor type `{actorInfo.Value.Name}` trait `{traitName}` field `{field.Name}` references an undefined sequence `{sequence}` on image `{i}`."); } } } @@ -123,7 +123,7 @@ namespace OpenRA.Mods.Common.Lint if (string.IsNullOrEmpty(image)) { if (!sequenceReference.AllowNullImage) - emitError("Weapon type `{0}` projectile field `{1}` must define a value".F(weaponInfo.Key, sequenceReference.ImageReference)); + emitError($"Weapon type `{weaponInfo.Key}` projectile field `{sequenceReference.ImageReference}` must define a value"); continue; } @@ -138,10 +138,10 @@ namespace OpenRA.Mods.Common.Lint { // TODO: Remove prefixed sequence references and instead use explicit lists of lintable references if (!sequences.Sequences(image).Any(s => s.StartsWith(sequence))) - emitWarning("Weapon type `{0}` projectile field `{1}` defines a prefix `{2}` that does not match any sequences on image `{3}`.".F(weaponInfo.Key, field.Name, sequence, image)); + emitWarning($"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` defines a prefix `{sequence}` that does not match any sequences on image `{image}`."); } else if (!sequences.HasSequence(image, sequence)) - emitError("Weapon type `{0}` projectile field `{1}` references an undefined sequence `{2}` on image `{3}`.".F(weaponInfo.Key, field.Name, sequence, image)); + emitError($"Weapon type `{weaponInfo.Key}` projectile field `{field.Name}` references an undefined sequence `{sequence}` on image `{image}`."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckSpriteBodies.cs b/OpenRA.Mods.Common/Lint/CheckSpriteBodies.cs index 5989a27f25..485e33ae42 100644 --- a/OpenRA.Mods.Common/Lint/CheckSpriteBodies.cs +++ b/OpenRA.Mods.Common/Lint/CheckSpriteBodies.cs @@ -35,7 +35,7 @@ namespace OpenRA.Mods.Common.Lint var wsbs = actorInfo.Value.TraitInfos(); foreach (var wsb in wsbs) if (wsbs.Any(w => w != wsb && w.Name == wsb.Name)) - emitError("Actor type `{0}` has more than one *SpriteBody with Name: {1}!".F(actorInfo.Key, wsb.Name)); + emitError($"Actor type `{actorInfo.Key}` has more than one *SpriteBody with Name: {wsb.Name}!"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckSyncAnnotations.cs b/OpenRA.Mods.Common/Lint/CheckSyncAnnotations.cs index a60cf138bb..d96bc1007b 100644 --- a/OpenRA.Mods.Common/Lint/CheckSyncAnnotations.cs +++ b/OpenRA.Mods.Common/Lint/CheckSyncAnnotations.cs @@ -49,14 +49,14 @@ namespace OpenRA.Mods.Common.Lint { foreach (var type in types) if (!TypeImplementsSync(type) && AnyTypeMemberIsSynced(type)) - emitWarning("{0} has members with the Sync attribute but does not implement ISync".F(type.FullName)); + emitWarning($"{type.FullName} has members with the Sync attribute but does not implement ISync"); } static void CheckTypesImplementingSyncInterfaceHaveSyncableMembers(IEnumerable types, Action emitWarning) { foreach (var type in types) if (TypeImplementsSync(type) && !AnyTypeMemberIsSynced(type)) - emitWarning("{0} implements ISync but does not use the Sync attribute on any members.".F(type.FullName)); + emitWarning($"{type.FullName} implements ISync but does not use the Sync attribute on any members."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckTraitLocation.cs b/OpenRA.Mods.Common/Lint/CheckTraitLocation.cs index faa2ad7fbb..fb573a5cf0 100644 --- a/OpenRA.Mods.Common/Lint/CheckTraitLocation.cs +++ b/OpenRA.Mods.Common/Lint/CheckTraitLocation.cs @@ -34,7 +34,7 @@ namespace OpenRA.Mods.Common.Lint var traitName = traitInfo.GetType().Name; traitName = traitName.Remove(traitName.Length - 4); var locations = traitLocation.SystemActors.ToString().Replace(", ", " or "); - emitError("{0} does not belong on {1}. It is a system trait meant for {2}.".F(traitName, actorInfo.Key, locations)); + emitError($"{traitName} does not belong on {actorInfo.Key}. It is a system trait meant for {locations}."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckTraitPrerequisites.cs b/OpenRA.Mods.Common/Lint/CheckTraitPrerequisites.cs index 34cf2f5bbb..2cf20dc2d9 100644 --- a/OpenRA.Mods.Common/Lint/CheckTraitPrerequisites.cs +++ b/OpenRA.Mods.Common/Lint/CheckTraitPrerequisites.cs @@ -35,11 +35,11 @@ namespace OpenRA.Mods.Common.Lint { var hasTraits = actorInfo.Value.TraitsInConstructOrder().Any(); if (!hasTraits) - emitWarning("Actor {0} has no traits. Is this intended?".F(actorInfo.Key)); + emitWarning($"Actor {actorInfo.Key} has no traits. Is this intended?"); } catch (Exception e) { - emitError("Actor {0} is not constructible; failure: {1}".F(actorInfo.Key, e.Message)); + emitError($"Actor {actorInfo.Key} is not constructible; failure: {e.Message}"); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs b/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs index 66d8f832fd..213640daf3 100644 --- a/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs +++ b/OpenRA.Mods.Common/Lint/CheckUnknownTraitFields.cs @@ -54,10 +54,10 @@ namespace OpenRA.Mods.Common.Lint if (t.Key.StartsWith("-", StringComparison.Ordinal)) { if (t.Value.Nodes.Any()) - emitError("{0} {1} defines child nodes, which are not valid for removals.".F(t.Location, t.Key)); + emitError($"{t.Location} {t.Key} defines child nodes, which are not valid for removals."); if (!string.IsNullOrEmpty(t.Value.Value)) - emitError("{0} {1} defines a value, which is not valid for removals.".F(t.Location, t.Key)); + emitError($"{t.Location} {t.Key} defines a value, which is not valid for removals."); continue; } @@ -67,7 +67,7 @@ namespace OpenRA.Mods.Common.Lint // Inherits can never define children if (traitName == "Inherits" && t.Value.Nodes.Any()) { - emitError("{0} defines child nodes, which are not valid for Inherits.".F(t.Location)); + emitError($"{t.Location} defines child nodes, which are not valid for Inherits."); continue; } @@ -76,7 +76,7 @@ namespace OpenRA.Mods.Common.Lint { var fieldName = NormalizeName(field.Key); if (traitInfo.GetField(fieldName) == null) - emitError("{0} refers to a trait field `{1}` that does not exist on `{2}`.".F(field.Location, fieldName, traitName)); + emitError($"{field.Location} refers to a trait field `{fieldName}` that does not exist on `{traitName}`."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs b/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs index d9b70f0465..f9ffcf831b 100644 --- a/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs +++ b/OpenRA.Mods.Common/Lint/CheckUnknownWeaponFields.cs @@ -56,10 +56,10 @@ namespace OpenRA.Mods.Common.Lint if (field.Key.StartsWith("-", StringComparison.Ordinal)) { if (field.Value.Nodes.Any()) - emitError("{0} {1} defines child nodes, which is not valid for removals.".F(field.Location, field.Key)); + emitError($"{field.Location} {field.Key} defines child nodes, which is not valid for removals."); if (!string.IsNullOrEmpty(field.Value.Value)) - emitError("{0} {1} defines a value, which is not valid for removals.".F(field.Location, field.Key)); + emitError($"{field.Location} {field.Key} defines a value, which is not valid for removals."); continue; } @@ -73,14 +73,14 @@ namespace OpenRA.Mods.Common.Lint { var projectileFieldName = NormalizeName(projectileField.Key); if (projectileInfo.GetField(projectileFieldName) == null) - emitError("{0} refers to a projectile field `{1}` that does not exist on `{2}`.".F(projectileField.Location, projectileFieldName, projectileName)); + emitError($"{projectileField.Location} refers to a projectile field `{projectileFieldName}` that does not exist on `{projectileName}`."); } } else if (fieldName == "Warhead") { if (string.IsNullOrEmpty(field.Value.Value)) { - emitWarning("{0} does not define a warhead type. Skipping unknown field check.".F(field.Location)); + emitWarning($"{field.Location} does not define a warhead type. Skipping unknown field check."); continue; } @@ -90,11 +90,11 @@ namespace OpenRA.Mods.Common.Lint { var warheadFieldName = NormalizeName(warheadField.Key); if (warheadInfo.GetField(warheadFieldName) == null) - emitError("{0} refers to a warhead field `{1}` that does not exist on `{2}`.".F(warheadField.Location, warheadFieldName, warheadName)); + emitError($"{warheadField.Location} refers to a warhead field `{warheadFieldName}` that does not exist on `{warheadName}`."); } } else if (fieldName != "Inherits" && weaponInfo.GetField(fieldName) == null) - emitError("{0} refers to a weapon field `{1}` that does not exist.".F(field.Location, fieldName)); + emitError($"{field.Location} refers to a weapon field `{fieldName}` that does not exist."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckVoiceReferences.cs b/OpenRA.Mods.Common/Lint/CheckVoiceReferences.cs index ddd888bd2a..55e989fd1a 100644 --- a/OpenRA.Mods.Common/Lint/CheckVoiceReferences.cs +++ b/OpenRA.Mods.Common/Lint/CheckVoiceReferences.cs @@ -67,7 +67,7 @@ namespace OpenRA.Mods.Common.Lint continue; if (!soundInfo.Voices.Keys.Contains(voice)) - emitError("Actor {0} using voice set {1} does not define {2} voice required by {3}.".F(actorInfo.Name, voiceSet, voice, traitInfo)); + emitError($"Actor {actorInfo.Name} using voice set {voiceSet} does not define {voice} voice required by {traitInfo}."); } } } diff --git a/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs b/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs index 2d968a4fe6..587afbaddd 100644 --- a/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs +++ b/OpenRA.Mods.Common/Lint/CheckWorldAndPlayerInherits.cs @@ -86,7 +86,7 @@ namespace OpenRA.Mods.Common.Lint foreach (var inherit in inherits) { if (inherit[0] != '^') - emitError("{0} definition inherits from {1}, which is not an abstract template.".F(actor, inherit)); + emitError($"{actor} definition inherits from {inherit}, which is not an abstract template."); toResolve.Enqueue(inherit); } diff --git a/OpenRA.Mods.Common/Lint/LintBuildablePrerequisites.cs b/OpenRA.Mods.Common/Lint/LintBuildablePrerequisites.cs index a0c9679dc8..4808ab7b8e 100644 --- a/OpenRA.Mods.Common/Lint/LintBuildablePrerequisites.cs +++ b/OpenRA.Mods.Common/Lint/LintBuildablePrerequisites.cs @@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.Lint foreach (var prereq in bi.Prerequisites) if (!prereq.StartsWith("~disabled")) if (!providedPrereqs.Contains(prereq.Replace("!", "").Replace("~", ""))) - emitError("Buildable actor {0} has prereq {1} not provided by anything.".F(i.Key, prereq)); + emitError($"Buildable actor {i.Key} has prereq {prereq} not provided by anything."); } } } diff --git a/OpenRA.Mods.Common/Lint/LintExts.cs b/OpenRA.Mods.Common/Lint/LintExts.cs index 3257c31ed1..6678dbfa8a 100644 --- a/OpenRA.Mods.Common/Lint/LintExts.cs +++ b/OpenRA.Mods.Common/Lint/LintExts.cs @@ -63,8 +63,7 @@ namespace OpenRA.Mods.Common.Lint "BooleanExpression", "IntegerExpression" }; - throw new InvalidOperationException("Bad type for reference on {0}.{1}. Supported types: {2}" - .F(ruleInfo.GetType().Name, fieldInfo.Name, supportedTypes.JoinWith(", "))); + throw new InvalidOperationException($"Bad type for reference on {ruleInfo.GetType().Name}.{fieldInfo.Name}. Supported types: {supportedTypes.JoinWith(", ")}"); } public static IEnumerable GetPropertyValues(object ruleInfo, PropertyInfo propertyInfo, Action emitError, @@ -109,8 +108,7 @@ namespace OpenRA.Mods.Common.Lint "BooleanExpression", "IntegerExpression" }; - throw new InvalidOperationException("Bad type for reference on {0}.{1}. Supported types: {2}" - .F(ruleInfo.GetType().Name, propertyInfo.Name, supportedTypes.JoinWith(", "))); + throw new InvalidOperationException($"Bad type for reference on {ruleInfo.GetType().Name}.{propertyInfo.Name}. Supported types: {supportedTypes.JoinWith(", ")}"); } } } diff --git a/OpenRA.Mods.Common/LoadScreens/BlankLoadScreen.cs b/OpenRA.Mods.Common/LoadScreens/BlankLoadScreen.cs index d6723a137a..ac95dba5b6 100644 --- a/OpenRA.Mods.Common/LoadScreens/BlankLoadScreen.cs +++ b/OpenRA.Mods.Common/LoadScreens/BlankLoadScreen.cs @@ -52,7 +52,7 @@ namespace OpenRA.Mods.Common.LoadScreens if (!string.IsNullOrEmpty(Launch.Benchmark)) { - Console.WriteLine("Saving benchmark data into {0}".F(Path.Combine(Platform.SupportDir, "Logs"))); + Console.WriteLine($"Saving benchmark data into {Path.Combine(Platform.SupportDir, "Logs")}"); Game.BenchmarkMode(Launch.Benchmark); } diff --git a/OpenRA.Mods.Common/Scripting/Global/ActorGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/ActorGlobal.cs index 6d20230d44..3862504f24 100644 --- a/OpenRA.Mods.Common/Scripting/Global/ActorGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/ActorGlobal.cs @@ -33,7 +33,7 @@ namespace OpenRA.Mods.Common.Scripting var initInstance = initName.Split(ActorInfo.TraitInstanceSeparator); var initType = Game.ModData.ObjectCreator.FindType(initInstance[0] + "Init"); if (initType == null) - throw new LuaException("Unknown initializer type '{0}'".F(initInstance[0])); + throw new LuaException($"Unknown initializer type '{initInstance[0]}'"); // Construct the ActorInit. var init = (ActorInit)FormatterServices.GetUninitializedObject(initType); @@ -51,14 +51,14 @@ namespace OpenRA.Mods.Common.Scripting { var key = kv.Key.ToString(); if (!args.TryGetValue(key, out var type)) - throw new LuaException("Unknown initializer type '{0}.{1}'".F(initInstance[0], key)); + throw new LuaException($"Unknown initializer type '{initInstance[0]}.{key}'"); var isActorReference = type == typeof(ActorInitActorReference); if (isActorReference) type = kv.Value is LuaString ? typeof(string) : typeof(Actor); if (!kv.Value.TryGetClrValue(type, out var clrValue)) - throw new LuaException("Invalid data type for '{0}.{1}' (expected {2}, got {3})".F(initInstance[0], key, type.Name, kv.Value.WrappedClrType())); + throw new LuaException($"Invalid data type for '{initInstance[0]}.{key}' (expected {type.Name}, got {kv.Value.WrappedClrType()})"); if (isActorReference) clrValue = type == typeof(string) ? new ActorInitActorReference((string)clrValue) : new ActorInitActorReference((Actor)clrValue); @@ -100,7 +100,7 @@ namespace OpenRA.Mods.Common.Scripting } var types = initializers.Select(y => y.GetParameters()[0].ParameterType.Name).JoinWith(", "); - throw new LuaException("Invalid data type for '{0}' (expected one of {1})".F(initInstance[0], types)); + throw new LuaException($"Invalid data type for '{initInstance[0]}' (expected one of {types})"); } [Desc("Create a new actor. initTable specifies a list of key-value pairs that defines the initial parameters for the actor's traits.")] @@ -118,7 +118,7 @@ namespace OpenRA.Mods.Common.Scripting var owner = initDict.GetOrDefault(); if (owner == null) - throw new LuaException("Tried to create actor '{0}' with an invalid or no owner init!".F(type)); + throw new LuaException($"Tried to create actor '{type}' with an invalid or no owner init!"); // The actor must be added to the world at the end of the tick var a = Context.World.CreateActor(false, type, initDict); @@ -133,7 +133,7 @@ namespace OpenRA.Mods.Common.Scripting public int BuildTime(string type, string queue = null) { if (!Context.World.Map.Rules.Actors.TryGetValue(type, out var ai)) - throw new LuaException("Unknown actor type '{0}'".F(type)); + throw new LuaException($"Unknown actor type '{type}'"); var bi = ai.TraitInfoOrDefault(); @@ -157,7 +157,7 @@ namespace OpenRA.Mods.Common.Scripting .Where(x => x.Type == queue)).FirstOrDefault(); if (pqueue == null) - throw new LuaException("The specified queue '{0}' does not exist!".F(queue)); + throw new LuaException($"The specified queue '{queue}' does not exist!"); pbi = pqueue.BuildDurationModifier; } @@ -167,7 +167,7 @@ namespace OpenRA.Mods.Common.Scripting .Where(x => bi.Queue.Contains(x.Type))).FirstOrDefault(); if (pqueue == null) - throw new LuaException("No actors can produce actor '{0}'!".F(type)); + throw new LuaException($"No actors can produce actor '{type}'!"); pbi = pqueue.BuildDurationModifier; } @@ -180,7 +180,7 @@ namespace OpenRA.Mods.Common.Scripting public int CruiseAltitude(string type) { if (!Context.World.Map.Rules.Actors.TryGetValue(type, out var ai)) - throw new LuaException("Unknown actor type '{0}'".F(type)); + throw new LuaException($"Unknown actor type '{type}'"); var pi = ai.TraitInfoOrDefault(); return pi != null ? pi.GetCruiseAltitude().Length : 0; @@ -189,11 +189,11 @@ namespace OpenRA.Mods.Common.Scripting public int Cost(string type) { if (!Context.World.Map.Rules.Actors.TryGetValue(type, out var ai)) - throw new LuaException("Unknown actor type '{0}'".F(type)); + throw new LuaException($"Unknown actor type '{type}'"); var vi = ai.TraitInfoOrDefault(); if (vi == null) - throw new LuaException("Actor type '{0}' does not have the Valued trait required to get the Cost.".F(type)); + throw new LuaException($"Actor type '{type}' does not have the Valued trait required to get the Cost."); return vi.Cost; } diff --git a/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs index 8c85ab27ed..0363dc676f 100644 --- a/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/ReinforcementsGlobal.cs @@ -36,7 +36,7 @@ namespace OpenRA.Mods.Common.Scripting Actor CreateActor(Player owner, string actorType, bool addToWorld, CPos? entryLocation = null, CPos? nextLocation = null) { if (!Context.World.Map.Rules.Actors.TryGetValue(actorType, out var ai)) - throw new LuaException("Unknown actor type '{0}'".F(actorType)); + throw new LuaException($"Unknown actor type '{actorType}'"); var initDict = new TypeDictionary(); diff --git a/OpenRA.Mods.Common/Scripting/Global/TriggerGlobal.cs b/OpenRA.Mods.Common/Scripting/Global/TriggerGlobal.cs index 0c20596074..9391176118 100644 --- a/OpenRA.Mods.Common/Scripting/Global/TriggerGlobal.cs +++ b/OpenRA.Mods.Common/Scripting/Global/TriggerGlobal.cs @@ -27,7 +27,7 @@ namespace OpenRA.Mods.Common.Scripting { var events = a.TraitOrDefault(); if (events == null) - throw new LuaException("Actor '{0}' requires the ScriptTriggers trait before attaching a trigger".F(a.Info.Name)); + throw new LuaException($"Actor '{a.Info.Name}' requires the ScriptTriggers trait before attaching a trigger"); return events; } diff --git a/OpenRA.Mods.Common/Scripting/Properties/AmmoPoolProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/AmmoPoolProperties.cs index dd8a47271b..18080c6966 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/AmmoPoolProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/AmmoPoolProperties.cs @@ -35,7 +35,7 @@ namespace OpenRA.Mods.Common.Scripting { var pool = ammoPools.FirstOrDefault(a => a.Info.Name == poolName); if (pool == null) - throw new LuaException("Invalid ammopool name {0} queried on actor {1}.".F(poolName, self)); + throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}."); return pool.CurrentAmmoCount; } @@ -45,7 +45,7 @@ namespace OpenRA.Mods.Common.Scripting { var pool = ammoPools.FirstOrDefault(a => a.Info.Name == poolName); if (pool == null) - throw new LuaException("Invalid ammopool name {0} queried on actor {1}.".F(poolName, self)); + throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}."); return pool.Info.Ammo; } @@ -56,7 +56,7 @@ namespace OpenRA.Mods.Common.Scripting { var pool = ammoPools.FirstOrDefault(a => a.Info.Name == poolName); if (pool == null) - throw new LuaException("Invalid ammopool name {0} queried on actor {1}.".F(poolName, self)); + throw new LuaException($"Invalid ammopool name {poolName} queried on actor {self}."); if (amount > 0) pool.GiveAmmo(self, amount); diff --git a/OpenRA.Mods.Common/Scripting/Properties/CaptureProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/CaptureProperties.cs index 99b7f79bc6..415402c74d 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/CaptureProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/CaptureProperties.cs @@ -33,7 +33,7 @@ namespace OpenRA.Mods.Common.Scripting { var targetManager = target.TraitOrDefault(); if (targetManager == null || !targetManager.CanBeTargetedBy(target, Self, captureManager)) - throw new LuaException("Actor '{0}' cannot capture actor '{1}'!".F(Self, target)); + throw new LuaException($"Actor '{Self}' cannot capture actor '{target}'!"); // NB: Scripted actions get no visible targetlines. Self.QueueActivity(new CaptureActor(Self, Target.FromActor(target), null)); diff --git a/OpenRA.Mods.Common/Scripting/Properties/ConditionProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/ConditionProperties.cs index a9d290ffb5..8d1e5cd02d 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/ConditionProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/ConditionProperties.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.Scripting .FirstOrDefault(t => t.Info.Condition == condition && t.CanGrantCondition(Self, this)); if (external == null) - throw new LuaException("Condition `{0}` has not been listed on an enabled ExternalCondition trait".F(condition)); + throw new LuaException($"Condition `{condition}` has not been listed on an enabled ExternalCondition trait"); return external.GrantCondition(Self, this, duration); } diff --git a/OpenRA.Mods.Common/Scripting/Properties/DeliveryProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/DeliveryProperties.cs index cb2eb9584d..90f051f933 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/DeliveryProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/DeliveryProperties.cs @@ -58,7 +58,7 @@ namespace OpenRA.Mods.Common.Scripting { var targetGainsExperience = target.TraitOrDefault(); if (targetGainsExperience == null) - throw new LuaException("Actor '{0}' cannot gain experience!".F(target)); + throw new LuaException($"Actor '{target}' cannot gain experience!"); if (targetGainsExperience.Level == targetGainsExperience.MaxLevel) return; diff --git a/OpenRA.Mods.Common/Scripting/Properties/GeneralProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/GeneralProperties.cs index e9f304a0dc..2778c6aade 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/GeneralProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/GeneralProperties.cs @@ -56,7 +56,7 @@ namespace OpenRA.Mods.Common.Scripting set { if (value == null) - throw new LuaException("Attempted to change the owner of actor '{0}' to nil value.".F(Self)); + throw new LuaException($"Attempted to change the owner of actor '{Self}' to nil value."); if (Self.Owner != value) Self.ChangeOwner(value); @@ -121,7 +121,7 @@ namespace OpenRA.Mods.Common.Scripting get { if (facing == null) - throw new LuaException("Actor '{0}' doesn't define a facing".F(Self)); + throw new LuaException($"Actor '{Self}' doesn't define a facing"); return facing.Facing; } @@ -172,7 +172,7 @@ namespace OpenRA.Mods.Common.Scripting return; if (!Enum.TryParse(value, true, out var stance)) - throw new LuaException("Unknown stance type '{0}'".F(value)); + throw new LuaException($"Unknown stance type '{value}'"); autotarget.PredictedStance = stance; autotarget.SetStance(Self, stance); diff --git a/OpenRA.Mods.Common/Scripting/Properties/PlayerConditionProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/PlayerConditionProperties.cs index a6b630f2dc..796b77eeea 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/PlayerConditionProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/PlayerConditionProperties.cs @@ -36,7 +36,7 @@ namespace OpenRA.Mods.Common.Scripting .FirstOrDefault(t => t.Info.Condition == condition && t.CanGrantCondition(Player.PlayerActor, this)); if (external == null) - throw new LuaException("Condition `{0}` has not been listed on an enabled ExternalCondition trait".F(condition)); + throw new LuaException($"Condition `{condition}` has not been listed on an enabled ExternalCondition trait"); return external.GrantCondition(Player.PlayerActor, this, duration); } diff --git a/OpenRA.Mods.Common/Scripting/Properties/PlayerProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/PlayerProperties.cs index d5ca90537d..06d1940df6 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/PlayerProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/PlayerProperties.cs @@ -91,7 +91,7 @@ namespace OpenRA.Mods.Common.Scripting var result = new List(); if (!Context.World.Map.Rules.Actors.TryGetValue(type, out var ai)) - throw new LuaException("Unknown actor type '{0}'".F(type)); + throw new LuaException($"Unknown actor type '{type}'"); result.AddRange(Player.World.Actors .Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && actor.Info.Name == ai.Name)); @@ -106,7 +106,7 @@ namespace OpenRA.Mods.Common.Scripting foreach (var type in types) if (!Context.World.Map.Rules.Actors.ContainsKey(type)) - throw new LuaException("Unknown actor type '{0}'".F(type)); + throw new LuaException($"Unknown actor type '{type}'"); result.AddRange(Player.World.Actors .Where(actor => actor.Owner == Player && !actor.IsDead && actor.IsInWorld && types.Contains(actor.Info.Name))); @@ -119,7 +119,7 @@ namespace OpenRA.Mods.Common.Scripting { var tt = Player.PlayerActor.TraitOrDefault(); if (tt == null) - throw new LuaException("Missing TechTree trait on player {0}!".F(Player)); + throw new LuaException($"Missing TechTree trait on player {Player}!"); return tt.HasPrerequisites(type); } diff --git a/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs b/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs index 14a710fd29..cbdb01848d 100644 --- a/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs +++ b/OpenRA.Mods.Common/Scripting/Properties/ProductionProperties.cs @@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Scripting public void Produce(string actorType, string factionVariant = null, string productionType = null) { if (!Self.World.Map.Rules.Actors.TryGetValue(actorType, out var actorInfo)) - throw new LuaException("Unknown actor type '{0}'".F(actorType)); + throw new LuaException($"Unknown actor type '{actorType}'"); var bi = actorInfo.TraitInfo(); Self.QueueActivity(new WaitFor(() => @@ -197,7 +197,7 @@ namespace OpenRA.Mods.Common.Scripting var bi = ri.TraitInfoOrDefault(); if (bi == null) - throw new LuaException("Actor of type {0} cannot be produced".F(actorType)); + throw new LuaException($"Actor of type {actorType} cannot be produced"); else return bi; } @@ -304,7 +304,7 @@ namespace OpenRA.Mods.Common.Scripting var bi = ri.TraitInfoOrDefault(); if (bi == null) - throw new LuaException("Actor of type {0} cannot be produced".F(actorType)); + throw new LuaException($"Actor of type {actorType} cannot be produced"); else return bi; } diff --git a/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs b/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs index d1db8e45d1..1d37079b45 100644 --- a/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs +++ b/OpenRA.Mods.Common/ServerTraits/LobbyCommands.cs @@ -80,7 +80,7 @@ namespace OpenRA.Mods.Common.Server if (server.State == ServerState.GameStarted) { - server.SendOrderTo(conn, "Message", "Cannot change state when game started. ({0})".F(cmd)); + server.SendOrderTo(conn, "Message", $"Cannot change state when game started. ({cmd})"); return false; } else if (client.State == Session.ClientState.Ready && !(cmd.StartsWith("state") || cmd == "startgame")) @@ -491,7 +491,7 @@ namespace OpenRA.Mods.Common.Server server.SyncLobbyInfo(); - server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); + server.SendMessage($"{client.Name} changed the map to {server.Map.Title}."); if ((server.LobbyInfo.GlobalSettings.MapStatus & Session.MapStatus.UnsafeCustomRules) != 0) server.SendMessage("This map contains custom rules. Game experience may change."); @@ -554,7 +554,7 @@ namespace OpenRA.Mods.Common.Server if (option.IsLocked) { - server.SendOrderTo(conn, "Message", "{0} cannot be changed.".F(option.Name)); + server.SendOrderTo(conn, "Message", $"{option.Name} cannot be changed."); return true; } @@ -588,7 +588,7 @@ namespace OpenRA.Mods.Common.Server if (!Exts.TryParseIntegerInvariant(s, out var teamCount)) { - server.SendOrderTo(conn, "Message", "Number of teams could not be parsed: {0}".F(s)); + server.SendOrderTo(conn, "Message", $"Number of teams could not be parsed: {s}"); return true; } @@ -653,7 +653,7 @@ namespace OpenRA.Mods.Common.Server } Log.Write("server", "Kicking client {0}.", kickClientID); - server.SendMessage("{0} kicked {1} from the server.".F(client.Name, kickClient.Name)); + server.SendMessage($"{client.Name} kicked {kickClient.Name} from the server."); server.SendOrderTo(kickConn, "ServerError", "You have been kicked from the server."); server.DropClient(kickConn); @@ -661,7 +661,7 @@ namespace OpenRA.Mods.Common.Server if (tempBan) { Log.Write("server", "Temporarily banning client {0} ({1}).", kickClientID, kickClient.IPAddress); - server.SendMessage("{0} temporarily banned {1} from the server.".F(client.Name, kickClient.Name)); + server.SendMessage($"{client.Name} temporarily banned {kickClient.Name} from the server."); server.TempBans.Add(kickClient.IPAddress); } @@ -701,8 +701,8 @@ namespace OpenRA.Mods.Common.Server foreach (var b in bots) b.BotControllerClientIndex = newAdminId; - server.SendMessage("{0} is now the admin.".F(newAdminClient.Name)); - Log.Write("server", "{0} is now the admin.".F(newAdminClient.Name)); + server.SendMessage($"{newAdminClient.Name} is now the admin."); + Log.Write("server", $"{newAdminClient.Name} is now the admin."); server.SyncLobbyClients(); return true; @@ -735,8 +735,8 @@ namespace OpenRA.Mods.Common.Server targetClient.Handicap = 0; targetClient.Color = Color.White; targetClient.State = Session.ClientState.NotReady; - server.SendMessage("{0} moved {1} to spectators.".F(client.Name, targetClient.Name)); - Log.Write("server", "{0} moved {1} to spectators.".F(client.Name, targetClient.Name)); + server.SendMessage($"{client.Name} moved {targetClient.Name} to spectators."); + Log.Write("server", $"{client.Name} moved {targetClient.Name} to spectators."); server.SyncLobbyClients(); CheckAutoStart(server); @@ -753,7 +753,7 @@ namespace OpenRA.Mods.Common.Server return true; Log.Write("server", "Player@{0} is now known as {1}.", conn.Socket.RemoteEndPoint, sanitizedName); - server.SendMessage("{0} is now known as {1}.".F(client.Name, sanitizedName)); + server.SendMessage($"{client.Name} is now known as {sanitizedName}."); client.Name = sanitizedName; server.SyncLobbyClients(); @@ -781,8 +781,8 @@ namespace OpenRA.Mods.Common.Server if (!factions.Contains(parts[1])) { - server.SendOrderTo(conn, "Message", "Invalid faction selected: {0}".F(parts[1])); - server.SendOrderTo(conn, "Message", "Supported values: {0}".F(factions.JoinWith(", "))); + server.SendOrderTo(conn, "Message", $"Invalid faction selected: {parts[1]}"); + server.SendOrderTo(conn, "Message", $"Supported values: {factions.JoinWith(", ")}"); return true; } @@ -1012,7 +1012,7 @@ namespace OpenRA.Mods.Common.Server var uid = server.LobbyInfo.GlobalSettings.Map; server.Map = server.ModData.MapCache[uid]; if (server.Map.Status != MapStatus.Available) - throw new InvalidOperationException("Map {0} not found".F(uid)); + throw new InvalidOperationException($"Map {uid} not found"); server.LobbyInfo.Slots = server.Map.Players.Players .Select(p => MakeSlotFromPlayerReference(p.Value)) diff --git a/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs b/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs index 246bdfb0f5..a760ca4fee 100644 --- a/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs +++ b/OpenRA.Mods.Common/ServerTraits/PlayerPinger.cs @@ -89,7 +89,7 @@ namespace OpenRA.Mods.Common.Server var client = server.GetClient(c); if (client != null) - server.SendMessage("{0} will be dropped in {1} seconds.".F(client.Name, (ConnTimeout - c.TimeSinceLastResponse) / 1000)); + server.SendMessage($"{client.Name} will be dropped in {(ConnTimeout - c.TimeSinceLastResponse) / 1000} seconds."); } } } diff --git a/OpenRA.Mods.Common/SpriteLoaders/DdsLoader.cs b/OpenRA.Mods.Common/SpriteLoaders/DdsLoader.cs index 67023ff6d3..0990dd368a 100644 --- a/OpenRA.Mods.Common/SpriteLoaders/DdsLoader.cs +++ b/OpenRA.Mods.Common/SpriteLoaders/DdsLoader.cs @@ -65,7 +65,7 @@ namespace OpenRA.Mods.Common.SpriteLoaders // SpriteFrameType refers to the channel byte order, which is reversed from the little-endian bit order case ImageFormat.Rgba32: Type = SpriteFrameType.Bgra32; break; case ImageFormat.Rgb24: Type = SpriteFrameType.Bgr24; break; - default: throw new InvalidDataException("Unhandled ImageFormat {0}".F(dds.Format)); + default: throw new InvalidDataException($"Unhandled ImageFormat {dds.Format}"); } } } diff --git a/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs b/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs index 2dc5bd9151..1e2bb445d5 100644 --- a/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs +++ b/OpenRA.Mods.Common/SpriteLoaders/PngSheetLoader.cs @@ -103,7 +103,7 @@ namespace OpenRA.Mods.Common.SpriteLoaders var coords = frame.Split(';'); var region = FieldLoader.GetValue("Region", coords[0]); if (!pngRectangle.Contains(region)) - throw new InvalidDataException("Invalid frame regions {0} defined.".F(region)); + throw new InvalidDataException($"Invalid frame regions {region} defined."); regions.Add(region); offsets.Add(FieldLoader.GetValue("Offset", coords[1])); @@ -146,7 +146,7 @@ namespace OpenRA.Mods.Common.SpriteLoaders var rows = (frameAmount + framesPerRow - 1) / framesPerRow; if (png.Width < frameSize.Width * frameAmount / rows || png.Height < frameSize.Height * rows) - throw new InvalidDataException("Invalid frame size {0} and frame amount {1} defined.".F(frameSize, frameAmount)); + throw new InvalidDataException($"Invalid frame size {frameSize} and frame amount {frameAmount} defined."); regions = new List(); offsets = new List(); diff --git a/OpenRA.Mods.Common/SpriteLoaders/TgaLoader.cs b/OpenRA.Mods.Common/SpriteLoaders/TgaLoader.cs index dd9a72e306..3de360361d 100644 --- a/OpenRA.Mods.Common/SpriteLoaders/TgaLoader.cs +++ b/OpenRA.Mods.Common/SpriteLoaders/TgaLoader.cs @@ -92,7 +92,7 @@ namespace OpenRA.Mods.Common.SpriteLoaders // SpriteFrameType refers to the channel byte order, which is reversed from the little-endian bit order case ImageFormat.Rgba32: Type = SpriteFrameType.Bgra32; break; case ImageFormat.Rgb24: Type = SpriteFrameType.Bgr24; break; - default: throw new InvalidDataException("Unhandled ImageFormat {0}".F(tga.Format)); + default: throw new InvalidDataException($"Unhandled ImageFormat {tga.Format}"); } } } diff --git a/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs b/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs index f033a19e4d..9a85e6230f 100644 --- a/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs +++ b/OpenRA.Mods.Common/Terrain/DefaultTerrain.cs @@ -106,7 +106,7 @@ namespace OpenRA.Mods.Common.Terrain var tt = TerrainInfo[i].Type; if (terrainIndexByType.ContainsKey(tt)) - throw new YamlException("Duplicate terrain type '{0}' in '{1}'.".F(tt, filepath)); + throw new YamlException($"Duplicate terrain type '{tt}' in '{filepath}'."); terrainIndexByType.Add(tt, i); } @@ -125,7 +125,7 @@ namespace OpenRA.Mods.Common.Terrain if (terrainIndexByType.TryGetValue(type, out var index)) return index; - throw new InvalidDataException("Tileset '{0}' lacks terrain type '{1}'".F(Id, type)); + throw new InvalidDataException($"Tileset '{Id}' lacks terrain type '{type}'"); } public byte GetTerrainIndex(TerrainTile r) diff --git a/OpenRA.Mods.Common/Terrain/DefaultTileCache.cs b/OpenRA.Mods.Common/Terrain/DefaultTileCache.cs index 7317b13316..0b24e18024 100644 --- a/OpenRA.Mods.Common/Terrain/DefaultTileCache.cs +++ b/OpenRA.Mods.Common/Terrain/DefaultTileCache.cs @@ -99,8 +99,7 @@ namespace OpenRA.Mods.Common.Terrain var start = indices.Min(); var end = indices.Max(); if (start < 0 || end >= frameCount) - throw new YamlException("Template `{0}` uses frames [{1}..{2}] of {3}, but only [0..{4}] actually exist" - .F(t.Key, start, end, i, frameCount - 1)); + throw new YamlException($"Template `{t.Key}` uses frames [{start}..{end}] of {i}, but only [0..{frameCount - 1}] actually exist"); variants.Add(indices.Select(j => { diff --git a/OpenRA.Mods.Common/Terrain/TerrainInfo.cs b/OpenRA.Mods.Common/Terrain/TerrainInfo.cs index 8d0f304482..aa4284f4c8 100644 --- a/OpenRA.Mods.Common/Terrain/TerrainInfo.cs +++ b/OpenRA.Mods.Common/Terrain/TerrainInfo.cs @@ -45,10 +45,10 @@ namespace OpenRA.Mods.Common.Terrain foreach (var node in nodes) { if (!int.TryParse(node.Key, out var key)) - throw new YamlException("Tileset `{0}` template `{1}` defines a frame `{2}` that is not a valid integer.".F(terrainInfo.Id, Id, node.Key)); + throw new YamlException($"Tileset `{terrainInfo.Id}` template `{Id}` defines a frame `{node.Key}` that is not a valid integer."); if (key < 0 || key >= tileInfo.Length) - throw new YamlException("Tileset `{0}` template `{1}` references frame {2}, but only [0..{3}] are valid for a {4}x{5} Size template.".F(terrainInfo.Id, Id, key, tileInfo.Length - 1, Size.X, Size.Y)); + throw new YamlException($"Tileset `{terrainInfo.Id}` template `{Id}` references frame {key}, but only [0..{tileInfo.Length - 1}] are valid for a {Size.X}x{Size.Y} Size template."); tileInfo[key] = LoadTileInfo(terrainInfo, node.Value); } @@ -61,10 +61,10 @@ namespace OpenRA.Mods.Common.Terrain foreach (var node in nodes) { if (!int.TryParse(node.Key, out var key)) - throw new YamlException("Tileset `{0}` template `{1}` defines a frame `{2}` that is not a valid integer.".F(terrainInfo.Id, Id, node.Key)); + throw new YamlException($"Tileset `{terrainInfo.Id}` template `{Id}` defines a frame `{node.Key}` that is not a valid integer."); if (key != i++) - throw new YamlException("Tileset `{0}` template `{1}` is missing a definition for frame {2}.".F(terrainInfo.Id, Id, i - 1)); + throw new YamlException($"Tileset `{terrainInfo.Id}` template `{Id}` is missing a definition for frame {i - 1}."); tileInfo[key] = LoadTileInfo(terrainInfo, node.Value); } diff --git a/OpenRA.Mods.Common/Traits/Air/FallsToEarth.cs b/OpenRA.Mods.Common/Traits/Air/FallsToEarth.cs index bad28a85da..1fc60ad449 100644 --- a/OpenRA.Mods.Common/Traits/Air/FallsToEarth.cs +++ b/OpenRA.Mods.Common/Traits/Air/FallsToEarth.cs @@ -42,7 +42,7 @@ namespace OpenRA.Mods.Common.Traits var weaponToLower = Explosion.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); ExplosionWeapon = weapon; } diff --git a/OpenRA.Mods.Common/Traits/Armament.cs b/OpenRA.Mods.Common/Traits/Armament.cs index ab9c84e152..e5016572ec 100644 --- a/OpenRA.Mods.Common/Traits/Armament.cs +++ b/OpenRA.Mods.Common/Traits/Armament.cs @@ -89,7 +89,7 @@ namespace OpenRA.Mods.Common.Traits { var weaponToLower = Weapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weaponInfo)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weaponInfo; ModifiedRange = new WDist(Util.ApplyPercentageModifiers( @@ -97,7 +97,7 @@ namespace OpenRA.Mods.Common.Traits ai.TraitInfos().Select(m => m.GetRangeModifierDefault()))); if (WeaponInfo.Burst > 1 && WeaponInfo.BurstDelays.Length > 1 && (WeaponInfo.BurstDelays.Length != WeaponInfo.Burst - 1)) - throw new YamlException("Weapon '{0}' has an invalid number of BurstDelays, must be single entry or Burst - 1.".F(weaponToLower)); + throw new YamlException($"Weapon '{weaponToLower}' has an invalid number of BurstDelays, must be single entry or Burst - 1."); base.RulesetLoaded(rules, ai); } diff --git a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs index 63cdb92f36..b0bcc03c61 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/BotModuleLogic/BaseBuilderQueueManager.cs @@ -166,7 +166,7 @@ namespace OpenRA.Mods.Common.Traits if (location == null) { - AIUtils.BotDebug("{0} has nowhere to place {1}".F(player, currentBuilding.Item)); + AIUtils.BotDebug($"{player} has nowhere to place {currentBuilding.Item}"); bot.QueueOrder(Order.CancelProduction(queue.Actor, currentBuilding.Item, 1)); failCount += failCount; diff --git a/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs b/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs index 7f2ef22312..4cdb78e03e 100644 --- a/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs +++ b/OpenRA.Mods.Common/Traits/BotModules/HarvesterBotModule.cs @@ -127,7 +127,7 @@ namespace OpenRA.Mods.Common.Traits // Tell the idle harvester to quit slacking: var newSafeResourcePatch = FindNextResource(h.Key, h.Value); - AIUtils.BotDebug("AI: Harvester {0} is idle. Ordering to {1} in search for new resources.".F(h.Key, newSafeResourcePatch)); + AIUtils.BotDebug($"AI: Harvester {h.Key} is idle. Ordering to {newSafeResourcePatch} in search for new resources."); bot.QueueOrder(new Order("Harvest", h.Key, newSafeResourcePatch, false)); } diff --git a/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs b/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs index 9ff5149c2e..af03260096 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/Bridge.cs @@ -63,7 +63,7 @@ namespace OpenRA.Mods.Common.Traits var weaponToLower = DemolishWeapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); DemolishWeaponInfo = weapon; } diff --git a/OpenRA.Mods.Common/Traits/Buildings/Building.cs b/OpenRA.Mods.Common/Traits/Buildings/Building.cs index 53cf7fdca0..197466d927 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/Building.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/Building.cs @@ -75,7 +75,7 @@ namespace OpenRA.Mods.Common.Traits { var fp = footprintYaml.Value.Value; var dims = dim.X + "x" + dim.Y; - throw new YamlException("Invalid footprint: {0} does not match dimensions {1}".F(fp, dims)); + throw new YamlException($"Invalid footprint: {fp} does not match dimensions {dims}"); } var index = 0; @@ -86,7 +86,7 @@ namespace OpenRA.Mods.Common.Traits { var c = footprintChars[index++]; if (!Enum.IsDefined(typeof(FootprintCellType), (FootprintCellType)c)) - throw new YamlException("Invalid footprint cell type '{0}'".F(c)); + throw new YamlException($"Invalid footprint cell type '{c}'"); ret[new CVec(x, y)] = (FootprintCellType)c; } diff --git a/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs b/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs index 2433d2b7a7..9ca510573b 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/FootprintPlaceBuildingPreview.cs @@ -65,9 +65,9 @@ namespace OpenRA.Mods.Common.Traits topLeftScreenOffset = -wr.ScreenPxOffset(centerOffset); var tileset = world.Map.Tileset.ToLowerInvariant(); - if (world.Map.Rules.Sequences.HasSequence("overlay", "build-valid-{0}".F(tileset))) + if (world.Map.Rules.Sequences.HasSequence("overlay", $"build-valid-{tileset}")) { - var validSequence = world.Map.Rules.Sequences.GetSequence("overlay", "build-valid-{0}".F(tileset)); + var validSequence = world.Map.Rules.Sequences.GetSequence("overlay", $"build-valid-{tileset}"); validTile = validSequence.GetSprite(0); validAlpha = validSequence.GetAlpha(0); } diff --git a/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs b/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs index d6b5c584e2..2f8c9b4fd7 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/GroundLevelBridge.cs @@ -38,7 +38,7 @@ namespace OpenRA.Mods.Common.Traits { var weaponToLower = (DemolishWeapon ?? string.Empty).ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); DemolishWeaponInfo = weapon; } diff --git a/OpenRA.Mods.Common/Traits/Buildings/Reservable.cs b/OpenRA.Mods.Common/Traits/Buildings/Reservable.cs index c94ef70409..78b5bb5836 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/Reservable.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/Reservable.cs @@ -61,8 +61,7 @@ namespace OpenRA.Mods.Common.Traits { if (Game.IsCurrentWorld(self.World)) throw new InvalidOperationException( - "Attempted to finalize an undisposed DisposableAction. {0} ({1}) reserved {2} ({3})".F( - forActor.Info.Name, forActor.ActorID, self.Info.Name, self.ActorID)); + $"Attempted to finalize an undisposed DisposableAction. {forActor.Info.Name} ({forActor.ActorID}) reserved {self.Info.Name} ({self.ActorID})"); })); } diff --git a/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs b/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs index 492f814835..8ebcb20c1e 100644 --- a/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs +++ b/OpenRA.Mods.Common/Traits/Buildings/TransformsIntoMobile.cs @@ -56,9 +56,9 @@ namespace OpenRA.Mods.Common.Traits var locomotorInfos = rules.Actors[SystemActors.World].TraitInfos(); LocomotorInfo = locomotorInfos.FirstOrDefault(li => li.Name == Locomotor); if (LocomotorInfo == null) - throw new YamlException("A locomotor named '{0}' doesn't exist.".F(Locomotor)); + throw new YamlException($"A locomotor named '{Locomotor}' doesn't exist."); else if (locomotorInfos.Count(li => li.Name == Locomotor) > 1) - throw new YamlException("There is more than one locomotor named '{0}'.".F(Locomotor)); + throw new YamlException($"There is more than one locomotor named '{Locomotor}'."); base.RulesetLoaded(rules, ai); } diff --git a/OpenRA.Mods.Common/Traits/CashTrickler.cs b/OpenRA.Mods.Common/Traits/CashTrickler.cs index ac087c678c..41f1a05b9c 100644 --- a/OpenRA.Mods.Common/Traits/CashTrickler.cs +++ b/OpenRA.Mods.Common/Traits/CashTrickler.cs @@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Traits void IRulesetLoaded.RulesetLoaded(Ruleset rules, ActorInfo info) { if (ShowTicks && !info.HasTraitInfo()) - throw new YamlException("CashTrickler is defined with ShowTicks 'true' but actor '{0}' occupies no space.".F(info.Name)); + throw new YamlException($"CashTrickler is defined with ShowTicks 'true' but actor '{info.Name}' occupies no space."); } public override object Create(ActorInitializer init) { return new CashTrickler(this); } diff --git a/OpenRA.Mods.Common/Traits/CombatDebugOverlay.cs b/OpenRA.Mods.Common/Traits/CombatDebugOverlay.cs index 7185aba9fb..e131f127ba 100644 --- a/OpenRA.Mods.Common/Traits/CombatDebugOverlay.cs +++ b/OpenRA.Mods.Common/Traits/CombatDebugOverlay.cs @@ -136,7 +136,7 @@ namespace OpenRA.Mods.Common.Traits return; var maxHP = healthInfo.MaxHP > 0 ? healthInfo.MaxHP : 1; - var damageText = "{0} ({1}%)".F(-e.Damage.Value, e.Damage.Value * 100 / maxHP); + var damageText = $"{-e.Damage.Value} ({e.Damage.Value * 100 / maxHP}%)"; self.World.AddFrameEndTask(w => w.Add(new FloatingText(self.CenterPosition, e.Attacker.Owner.Color, damageText, 30))); } diff --git a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnHealth.cs b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnHealth.cs index 6af18eb97c..f18d6748df 100644 --- a/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnHealth.cs +++ b/OpenRA.Mods.Common/Traits/Conditions/GrantConditionOnHealth.cs @@ -43,7 +43,7 @@ namespace OpenRA.Mods.Common.Traits { var health = ai.TraitInfo(); if (health.MaxHP < MinHP) - throw new YamlException("Minimum HP ({0}) for GrantConditionOnHealth can't be more than actor's Maximum HP ({1})".F(MinHP, health.MaxHP)); + throw new YamlException($"Minimum HP ({MinHP}) for GrantConditionOnHealth can't be more than actor's Maximum HP ({health.MaxHP})"); } } diff --git a/OpenRA.Mods.Common/Traits/Explodes.cs b/OpenRA.Mods.Common/Traits/Explodes.cs index d5d081c503..6e46030dbc 100644 --- a/OpenRA.Mods.Common/Traits/Explodes.cs +++ b/OpenRA.Mods.Common/Traits/Explodes.cs @@ -65,7 +65,7 @@ namespace OpenRA.Mods.Common.Traits { var weaponToLower = Weapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weapon; } @@ -73,7 +73,7 @@ namespace OpenRA.Mods.Common.Traits { var emptyWeaponToLower = EmptyWeapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(emptyWeaponToLower, out var emptyWeapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(emptyWeaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{emptyWeaponToLower}'"); EmptyWeaponInfo = emptyWeapon; } diff --git a/OpenRA.Mods.Common/Traits/ExplosionOnDamageTransition.cs b/OpenRA.Mods.Common/Traits/ExplosionOnDamageTransition.cs index d1aeb4722b..f5e579fbe5 100644 --- a/OpenRA.Mods.Common/Traits/ExplosionOnDamageTransition.cs +++ b/OpenRA.Mods.Common/Traits/ExplosionOnDamageTransition.cs @@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common.Traits var weaponToLower = Weapon.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weapon; } diff --git a/OpenRA.Mods.Common/Traits/HitShape.cs b/OpenRA.Mods.Common/Traits/HitShape.cs index ca7df6b2a9..e45576f83b 100644 --- a/OpenRA.Mods.Common/Traits/HitShape.cs +++ b/OpenRA.Mods.Common/Traits/HitShape.cs @@ -54,7 +54,7 @@ namespace OpenRA.Mods.Common.Traits } catch (YamlException e) { - throw new YamlException("HitShape {0}: {1}".F(shape, e.Message)); + throw new YamlException($"HitShape {shape}: {e.Message}"); } } else diff --git a/OpenRA.Mods.Common/Traits/Mobile.cs b/OpenRA.Mods.Common/Traits/Mobile.cs index cb05662534..7743746956 100644 --- a/OpenRA.Mods.Common/Traits/Mobile.cs +++ b/OpenRA.Mods.Common/Traits/Mobile.cs @@ -90,9 +90,9 @@ namespace OpenRA.Mods.Common.Traits var locomotorInfos = rules.Actors[SystemActors.World].TraitInfos(); LocomotorInfo = locomotorInfos.FirstOrDefault(li => li.Name == Locomotor); if (LocomotorInfo == null) - throw new YamlException("A locomotor named '{0}' doesn't exist.".F(Locomotor)); + throw new YamlException($"A locomotor named '{Locomotor}' doesn't exist."); else if (locomotorInfos.Count(li => li.Name == Locomotor) > 1) - throw new YamlException("There is more than one locomotor named '{0}'.".F(Locomotor)); + throw new YamlException($"There is more than one locomotor named '{Locomotor}'."); // We need to reset the reference to the locomotor between each worlds, otherwise we are reference the previous state. locomotor = null; diff --git a/OpenRA.Mods.Common/Traits/Player/DeveloperMode.cs b/OpenRA.Mods.Common/Traits/Player/DeveloperMode.cs index 4d42ec1097..f7777e88f8 100644 --- a/OpenRA.Mods.Common/Traits/Player/DeveloperMode.cs +++ b/OpenRA.Mods.Common/Traits/Player/DeveloperMode.cs @@ -176,7 +176,7 @@ namespace OpenRA.Mods.Common.Traits var amount = order.ExtraData != 0 ? (int)order.ExtraData : info.Cash; self.Trait().ChangeCash(amount); - debugSuffix = " ({0} credits)".F(amount); + debugSuffix = $" ({amount} credits)"; break; } @@ -188,7 +188,7 @@ namespace OpenRA.Mods.Common.Traits foreach (var player in receivingPlayers) player.PlayerActor.Trait().ChangeCash(amount); - debugSuffix = " ({0} credits)".F(amount); + debugSuffix = $" ({amount} credits)"; break; } diff --git a/OpenRA.Mods.Common/Traits/Player/TimeLimitManager.cs b/OpenRA.Mods.Common/Traits/Player/TimeLimitManager.cs index 6d06f5c86f..c3b09e87ee 100644 --- a/OpenRA.Mods.Common/Traits/Player/TimeLimitManager.cs +++ b/OpenRA.Mods.Common/Traits/Player/TimeLimitManager.cs @@ -81,7 +81,7 @@ namespace OpenRA.Mods.Common.Traits if (c == 0) return "No limit"; else - return c.ToString() + " minute{0}".F(c > 1 ? "s" : null); + return c.ToString() + $" minute{(c > 1 ? "s" : null)}"; }); yield return new LobbyOption("timelimit", TimeLimitLabel, TimeLimitDescription, TimeLimitDropdownVisible, TimeLimitDisplayOrder, diff --git a/OpenRA.Mods.Common/Traits/PowerTooltip.cs b/OpenRA.Mods.Common/Traits/PowerTooltip.cs index 3e028d64b1..7f3bf3c2b0 100644 --- a/OpenRA.Mods.Common/Traits/PowerTooltip.cs +++ b/OpenRA.Mods.Common/Traits/PowerTooltip.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.Traits return forPlayer == self.Owner; } - public string TooltipText => "Power Usage: {0}{1}".F(powerManager.PowerDrained, developerMode.UnlimitedPower ? "" : "/" + powerManager.PowerProvided); + public string TooltipText => $"Power Usage: {powerManager.PowerDrained}{(developerMode.UnlimitedPower ? "" : "/" + powerManager.PowerProvided)}"; public void OnOwnerChanged(Actor self, Player oldOwner, Player newOwner) { diff --git a/OpenRA.Mods.Common/Traits/Render/ProductionBar.cs b/OpenRA.Mods.Common/Traits/Render/ProductionBar.cs index 1b659d49e6..0379178b13 100644 --- a/OpenRA.Mods.Common/Traits/Render/ProductionBar.cs +++ b/OpenRA.Mods.Common/Traits/Render/ProductionBar.cs @@ -34,7 +34,7 @@ namespace OpenRA.Mods.Common.Traits.Render queue = rules.Actors[SystemActors.Player].TraitInfos().FirstOrDefault(q => ProductionType == q.Type); if (queue == null) - throw new YamlException("Can't find a queue with ProductionType '{0}'".F(ProductionType)); + throw new YamlException($"Can't find a queue with ProductionType '{ProductionType}'"); base.RulesetLoaded(rules, ai); } diff --git a/OpenRA.Mods.Common/Traits/Render/RenderDebugState.cs b/OpenRA.Mods.Common/Traits/Render/RenderDebugState.cs index a0400af0d8..ea1f90899c 100644 --- a/OpenRA.Mods.Common/Traits/Render/RenderDebugState.cs +++ b/OpenRA.Mods.Common/Traits/Render/RenderDebugState.cs @@ -94,7 +94,7 @@ namespace OpenRA.Mods.Common.Traits.Render if (squad == null) yield break; - var aiSquadInfo = "{0}, {1}".F(squad.Type, squad.TargetActor); + var aiSquadInfo = $"{squad.Type}, {squad.TargetActor}"; yield return new TextAnnotationRenderable(font, self.CenterPosition + offset, 0, color, aiSquadInfo); } diff --git a/OpenRA.Mods.Common/Traits/Render/WithNameTagDecoration.cs b/OpenRA.Mods.Common/Traits/Render/WithNameTagDecoration.cs index f978dc2e1d..ce105fa524 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithNameTagDecoration.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithNameTagDecoration.cs @@ -36,7 +36,7 @@ namespace OpenRA.Mods.Common.Traits.Render public override void RulesetLoaded(Ruleset rules, ActorInfo ai) { if (!Game.ModData.Manifest.Get().FontList.ContainsKey(Font)) - throw new YamlException("Font '{0}' is not listed in the mod.yaml's Fonts section".F(Font)); + throw new YamlException($"Font '{Font}' is not listed in the mod.yaml's Fonts section"); base.RulesetLoaded(rules, ai); } diff --git a/OpenRA.Mods.Common/Traits/Render/WithTextControlGroupDecoration.cs b/OpenRA.Mods.Common/Traits/Render/WithTextControlGroupDecoration.cs index e1d2707342..3828e95716 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithTextControlGroupDecoration.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithTextControlGroupDecoration.cs @@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.Traits.Render void IRulesetLoaded.RulesetLoaded(Ruleset rules, ActorInfo info) { if (!Game.ModData.Manifest.Get().FontList.ContainsKey(Font)) - throw new YamlException("Font '{0}' is not listed in the mod.yaml's Fonts section".F(Font)); + throw new YamlException($"Font '{Font}' is not listed in the mod.yaml's Fonts section"); } public override object Create(ActorInitializer init) { return new WithTextControlGroupDecoration(init.Self, this); } diff --git a/OpenRA.Mods.Common/Traits/Render/WithTextDecoration.cs b/OpenRA.Mods.Common/Traits/Render/WithTextDecoration.cs index 0058ac6cd6..77ee5b08c5 100644 --- a/OpenRA.Mods.Common/Traits/Render/WithTextDecoration.cs +++ b/OpenRA.Mods.Common/Traits/Render/WithTextDecoration.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.Traits.Render public override void RulesetLoaded(Ruleset rules, ActorInfo ai) { if (!Game.ModData.Manifest.Get().FontList.ContainsKey(Font)) - throw new YamlException("Font '{0}' is not listed in the mod.yaml's Fonts section".F(Font)); + throw new YamlException($"Font '{Font}' is not listed in the mod.yaml's Fonts section"); base.RulesetLoaded(rules, ai); } diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs index d1f7b027aa..53abf55075 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/NukePower.cs @@ -128,7 +128,7 @@ namespace OpenRA.Mods.Common.Traits var weaponToLower = (MissileWeapon ?? string.Empty).ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); WeaponInfo = weapon; diff --git a/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs b/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs index 63986f0804..9945658738 100644 --- a/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs +++ b/OpenRA.Mods.Common/Traits/SupportPowers/ParatroopersPower.cs @@ -103,7 +103,7 @@ namespace OpenRA.Mods.Common.Traits var utLower = info.UnitType.ToLowerInvariant(); if (!self.World.Map.Rules.Actors.TryGetValue(utLower, out var unitType)) - throw new YamlException("Actors ruleset does not include the entry '{0}'".F(utLower)); + throw new YamlException($"Actors ruleset does not include the entry '{utLower}'"); var altitude = unitType.TraitInfo().CruiseAltitude.Length; var dropRotation = WRot.FromYaw(facing.Value); diff --git a/OpenRA.Mods.Common/Traits/ThrowsShrapnel.cs b/OpenRA.Mods.Common/Traits/ThrowsShrapnel.cs index f576d8f40d..ae460149a9 100644 --- a/OpenRA.Mods.Common/Traits/ThrowsShrapnel.cs +++ b/OpenRA.Mods.Common/Traits/ThrowsShrapnel.cs @@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.Traits { var weaponToLower = w.ToLowerInvariant(); if (!rules.Weapons.TryGetValue(weaponToLower, out var weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(weaponToLower)); + throw new YamlException($"Weapons Ruleset does not contain an entry '{weaponToLower}'"); return weapon; }).ToArray(); } diff --git a/OpenRA.Mods.Common/Traits/World/ActorSpawnManager.cs b/OpenRA.Mods.Common/Traits/World/ActorSpawnManager.cs index 0dbb3d0e69..fc8c09e2a9 100644 --- a/OpenRA.Mods.Common/Traits/World/ActorSpawnManager.cs +++ b/OpenRA.Mods.Common/Traits/World/ActorSpawnManager.cs @@ -45,13 +45,13 @@ namespace OpenRA.Mods.Common.Traits base.RulesetLoaded(rules, ai); if (SpawnInterval.Length == 0 || SpawnInterval.Length > 2) - throw new YamlException("{0}.{1} must be either 1 or 2 values".F(nameof(ActorSpawnManager), nameof(SpawnInterval))); + throw new YamlException($"{nameof(ActorSpawnManager)}.{nameof(SpawnInterval)} must be either 1 or 2 values"); if (SpawnInterval.Length == 2 && SpawnInterval[0] >= SpawnInterval[1]) - throw new YamlException("{0}.{1}'s first value must be less than the second value".F(nameof(ActorSpawnManager), nameof(SpawnInterval))); + throw new YamlException($"{nameof(ActorSpawnManager)}.{nameof(SpawnInterval)}'s first value must be less than the second value"); if (SpawnInterval.Any(it => it < 0)) - throw new YamlException("{0}.{1}'s value(s) must not be less than 0".F(nameof(ActorSpawnManager), nameof(SpawnInterval))); + throw new YamlException($"{nameof(ActorSpawnManager)}.{nameof(SpawnInterval)}'s value(s) must not be less than 0"); } public override object Create(ActorInitializer init) { return new ActorSpawnManager(init.Self, this); } diff --git a/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs b/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs index 460f9dab2c..a46adc46db 100644 --- a/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs +++ b/OpenRA.Mods.Common/Traits/World/CreateMapPlayers.cs @@ -103,7 +103,7 @@ namespace OpenRA.Mods.Common.Traits } if (!worldOwnerFound) - throw new InvalidOperationException("Map {0} does not define a player actor owning the world.".F(w.Map.Title)); + throw new InvalidOperationException($"Map {w.Map.Title} does not define a player actor owning the world."); Player localPlayer = null; diff --git a/OpenRA.Mods.Common/Traits/World/DomainIndex.cs b/OpenRA.Mods.Common/Traits/World/DomainIndex.cs index 7c72697c42..63d306a2ca 100644 --- a/OpenRA.Mods.Common/Traits/World/DomainIndex.cs +++ b/OpenRA.Mods.Common/Traits/World/DomainIndex.cs @@ -78,7 +78,7 @@ namespace OpenRA.Mods.Common.Traits domains = new CellLayer(world.Map); transientConnections = new Dictionary>(); - using (new PerfTimer("BuildDomains: {0} for movement class {1}".F(world.Map.Title, movementClass))) + using (new PerfTimer($"BuildDomains: {world.Map.Title} for movement class {movementClass}")) BuildDomains(world); } diff --git a/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs b/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs index defe2af298..5d66704103 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorActorLayer.cs @@ -205,12 +205,12 @@ namespace OpenRA.Mods.Common.Traits for (var index = 0; index < newCount; index++) { - if (Players.Players.ContainsKey("Multi{0}".F(index))) + if (Players.Players.ContainsKey($"Multi{index}")) continue; var pr = new PlayerReference { - Name = "Multi{0}".F(index), + Name = $"Multi{index}", Faction = "Random", Playable = true, Enemies = new[] { "Creeps" } diff --git a/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs b/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs index 4d39d52a37..4ea64fe2d5 100644 --- a/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs +++ b/OpenRA.Mods.Common/Traits/World/EditorActorPreview.cs @@ -64,7 +64,7 @@ namespace OpenRA.Mods.Common.Traits var world = worldRenderer.World; if (!world.Map.Rules.Actors.TryGetValue(reference.Type.ToLowerInvariant(), out Info)) - throw new InvalidDataException("Actor {0} of unknown type {1}".F(id, reference.Type.ToLowerInvariant())); + throw new InvalidDataException($"Actor {id} of unknown type {reference.Type.ToLowerInvariant()}"); CenterPosition = PreviewPosition(world, reference); @@ -241,7 +241,7 @@ namespace OpenRA.Mods.Common.Traits return world.Map.CenterOfSubCell(cell, subCell) + offset; } else - throw new InvalidDataException("Actor {0} must define Location or CenterPosition".F(ID)); + throw new InvalidDataException($"Actor {ID} must define Location or CenterPosition"); } void GeneratePreviews() @@ -259,7 +259,7 @@ namespace OpenRA.Mods.Common.Traits public override string ToString() { - return "{0} {1}".F(Info.Name, ID); + return $"{Info.Name} {ID}"; } public bool Equals(EditorActorPreview other) diff --git a/OpenRA.Mods.Common/Traits/World/ExitsDebugOverlayManager.cs b/OpenRA.Mods.Common/Traits/World/ExitsDebugOverlayManager.cs index 23463080db..0fb8b4d222 100644 --- a/OpenRA.Mods.Common/Traits/World/ExitsDebugOverlayManager.cs +++ b/OpenRA.Mods.Common/Traits/World/ExitsDebugOverlayManager.cs @@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common.Traits Info = info; if (!Game.Renderer.Fonts.TryGetValue(info.Font, out Font)) - throw new YamlException("Could not find font '{0}'".F(info.Font)); + throw new YamlException($"Could not find font '{info.Font}'"); } void IWorldLoaded.WorldLoaded(World w, WorldRenderer wr) diff --git a/OpenRA.Mods.Common/Traits/World/IndexedPalette.cs b/OpenRA.Mods.Common/Traits/World/IndexedPalette.cs index 43ef7280fd..0d6ce5824b 100644 --- a/OpenRA.Mods.Common/Traits/World/IndexedPalette.cs +++ b/OpenRA.Mods.Common/Traits/World/IndexedPalette.cs @@ -46,7 +46,7 @@ namespace OpenRA.Mods.Common public void RulesetLoaded(Ruleset rules, ActorInfo ai) { if (Index.Length != ReplaceIndex.Length) - throw new YamlException("ReplaceIndex length does not match Index length for palette {0}".F(Name)); + throw new YamlException($"ReplaceIndex length does not match Index length for palette {Name}"); } } diff --git a/OpenRA.Mods.Common/Traits/World/IndexedPlayerPalette.cs b/OpenRA.Mods.Common/Traits/World/IndexedPlayerPalette.cs index aa3781e61b..699fffdeb2 100644 --- a/OpenRA.Mods.Common/Traits/World/IndexedPlayerPalette.cs +++ b/OpenRA.Mods.Common/Traits/World/IndexedPlayerPalette.cs @@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common { foreach (var p in PlayerIndex) if (p.Value.Length != RemapIndex.Length) - throw new YamlException("PlayerIndex for player `{0}` length does not match RemapIndex!".F(p.Key)); + throw new YamlException($"PlayerIndex for player `{p.Key}` length does not match RemapIndex!"); } } diff --git a/OpenRA.Mods.Common/Traits/World/MapOptions.cs b/OpenRA.Mods.Common/Traits/World/MapOptions.cs index 2faf78af9a..9ba192c547 100644 --- a/OpenRA.Mods.Common/Traits/World/MapOptions.cs +++ b/OpenRA.Mods.Common/Traits/World/MapOptions.cs @@ -97,7 +97,7 @@ namespace OpenRA.Mods.Common.Traits { var gameSpeeds = Game.ModData.Manifest.Get().Speeds; if (GameSpeed != null && !gameSpeeds.ContainsKey(GameSpeed)) - throw new YamlException("Invalid default game speed '{0}'.".F(GameSpeed)); + throw new YamlException($"Invalid default game speed '{GameSpeed}'."); } public override object Create(ActorInitializer init) { return new MapOptions(this); } diff --git a/OpenRA.Mods.Common/Traits/World/PaletteFromGimpOrJascFile.cs b/OpenRA.Mods.Common/Traits/World/PaletteFromGimpOrJascFile.cs index 03222ca820..cb4c3531f5 100644 --- a/OpenRA.Mods.Common/Traits/World/PaletteFromGimpOrJascFile.cs +++ b/OpenRA.Mods.Common/Traits/World/PaletteFromGimpOrJascFile.cs @@ -62,7 +62,7 @@ namespace OpenRA.Mods.Common.Traits using (var lines = s.ReadAllLines().GetEnumerator()) { if (!lines.MoveNext() || (lines.Current != "GIMP Palette" && lines.Current != "JASC-PAL")) - throw new InvalidDataException("File `{0}` is not a valid GIMP or JASC palette.".F(Filename)); + throw new InvalidDataException($"File `{Filename}` is not a valid GIMP or JASC palette."); byte a; a = 255; @@ -76,16 +76,16 @@ namespace OpenRA.Mods.Common.Traits var rgba = lines.Current.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); if (rgba.Length < 3) - throw new InvalidDataException("Invalid RGB(A) triplet/quartet: ({0})".F(string.Join(" ", rgba))); + throw new InvalidDataException($"Invalid RGB(A) triplet/quartet: ({string.Join(" ", rgba)})"); if (!byte.TryParse(rgba[0], out var r)) - throw new InvalidDataException("Invalid R value: {0}".F(rgba[0])); + throw new InvalidDataException($"Invalid R value: {rgba[0]}"); if (!byte.TryParse(rgba[1], out var g)) - throw new InvalidDataException("Invalid G value: {0}".F(rgba[1])); + throw new InvalidDataException($"Invalid G value: {rgba[1]}"); if (!byte.TryParse(rgba[2], out var b)) - throw new InvalidDataException("Invalid B value: {0}".F(rgba[2])); + throw new InvalidDataException($"Invalid B value: {rgba[2]}"); // Check if color has a (valid) alpha value. // Note: We can't throw on "rgba.Length > 3 but parse failed", because in GIMP palettes the 'invalid' value is probably a color name string. diff --git a/OpenRA.Mods.Common/Traits/World/PaletteFromPng.cs b/OpenRA.Mods.Common/Traits/World/PaletteFromPng.cs index e34029bcc0..1dfc23037e 100644 --- a/OpenRA.Mods.Common/Traits/World/PaletteFromPng.cs +++ b/OpenRA.Mods.Common/Traits/World/PaletteFromPng.cs @@ -51,7 +51,7 @@ namespace OpenRA.Mods.Common.Traits var png = new Png(fileSystem.Open(Filename)); if (png.Palette == null) - throw new InvalidOperationException("Unable to load palette `{0}` from non-paletted png `{1}`".F(Name, Filename)); + throw new InvalidOperationException($"Unable to load palette `{Name}` from non-paletted png `{Filename}`"); var colors = new uint[Palette.Size]; diff --git a/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs b/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs index e4beec766a..9a92522a9d 100644 --- a/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs +++ b/OpenRA.Mods.Common/Traits/World/SpawnStartingUnits.cs @@ -81,7 +81,7 @@ namespace OpenRA.Mods.Common.Traits .RandomOrDefault(w.SharedRandom); if (unitGroup == null) - throw new InvalidOperationException("No starting units defined for faction {0} with class {1}".F(p.Faction.InternalName, spawnClass)); + throw new InvalidOperationException($"No starting units defined for faction {p.Faction.InternalName} with class {spawnClass}"); if (unitGroup.BaseActor != null) { @@ -108,7 +108,7 @@ namespace OpenRA.Mods.Common.Traits if (validCell == CPos.Zero) { - Log.Write("debug", "No cells available to spawn starting unit {0} for player {1}".F(s, p)); + Log.Write("debug", $"No cells available to spawn starting unit {s} for player {p}"); continue; } diff --git a/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs b/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs index cbe279ff76..efa56b0050 100644 --- a/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs +++ b/OpenRA.Mods.Common/Traits/World/TerrainRenderer.cs @@ -28,7 +28,7 @@ namespace OpenRA.Mods.Common.Traits var failed = false; Action onMissingImage = (id, f) => { - onError("\tTemplate `{0}` references sprite `{1}` that does not exist.".F(id, f)); + onError($"\tTemplate `{id}` references sprite `{f}` that does not exist."); missingImages.Add(f); failed = true; }; @@ -46,7 +46,7 @@ namespace OpenRA.Mods.Common.Traits if (t.Value[i] == null || tileCache.HasTileSprite(new TerrainTile(t.Key, (byte)i), v)) continue; - onError("\tTemplate `{0}` references frame {1} that does not exist in sprite `{2}`.".F(t.Key, i, templateInfo.Images[v])); + onError($"\tTemplate `{t.Key}` references frame {i} that does not exist in sprite `{templateInfo.Images[v]}`."); failed = true; } } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/AddResourceRenderer.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/AddResourceRenderer.cs index 0dc47ffb96..a635bea8a3 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/AddResourceRenderer.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/AddResourceRenderer.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { if (actorNode.ChildrenMatching("ResourceLayer").Any() && !actorNode.ChildrenMatching("ResourceRenderer").Any()) { - locations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); var resourceRenderer = new MiniYamlNode("ResourceRenderer", ""); resourceRenderer.AddNode("RenderTypes", ""); actorNode.AddNode(resourceRenderer); @@ -47,7 +47,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { actorNode.RenameChildrenMatching("D2kResourceLayer", "ResourceLayer"); - locations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); var resourceRenderer = new MiniYamlNode("D2kResourceRenderer", ""); resourceRenderer.AddNode("RenderTypes", ""); actorNode.AddNode(resourceRenderer); diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/CreateScreenShakeWarhead.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/CreateScreenShakeWarhead.cs index cc5223c6b9..b5fd74db11 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/CreateScreenShakeWarhead.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/CreateScreenShakeWarhead.cs @@ -34,7 +34,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules var weaponNode = madTankTrait.ChildrenMatching("MADTankThump").FirstOrDefault(); var weaponName = weaponNode != null ? weaponNode.Value.Value : "MADTankThump"; - weaponsToUpdate.Add(new Tuple(weaponName, traitName, "{0} ({1})".F(actorNode.Key, actorNode.Location.Filename))); + weaponsToUpdate.Add(new Tuple(weaponName, traitName, $"{actorNode.Key} ({actorNode.Location.Filename})")); madTankTrait.RemoveNodes("ThumpShakeTime"); madTankTrait.RemoveNodes("ThumpShakeIntensity"); @@ -50,7 +50,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules var weaponName = weaponNode.Value.Value; - weaponsToUpdate.Add(new Tuple(weaponName, traitName, "{0} ({1})".F(actorNode.Key, actorNode.Location.Filename))); + weaponsToUpdate.Add(new Tuple(weaponName, traitName, $"{actorNode.Key} ({actorNode.Location.Filename})")); } yield break; @@ -60,7 +60,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { if (weaponsToUpdate.Any()) yield return "Add a ScreenShakeWarhead to the following weapons:\n" + - UpdateUtils.FormatMessageList(weaponsToUpdate.Select(x => "Weapon `{0}`, used by trait `{1}` on actor {2}".F(x.Item1, x.Item2, x.Item3))); + UpdateUtils.FormatMessageList(weaponsToUpdate.Select(x => $"Weapon `{x.Item1}`, used by trait `{x.Item2}` on actor {x.Item3}")); weaponsToUpdate.Clear(); } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/ReformatChromeProvider.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/ReformatChromeProvider.cs index 0be1fe7df9..0b85d2fe5b 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/ReformatChromeProvider.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/ReformatChromeProvider.cs @@ -187,7 +187,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules regionsNode.AddNode(n.Key, n.NodeValue()); if (n.Value.Nodes.Any()) - overrideLocations.Add("{0}.{1} ({2})".F(chromeProviderNode.Key, n.Key, chromeProviderNode.Location.Filename)); + overrideLocations.Add($"{chromeProviderNode.Key}.{n.Key} ({chromeProviderNode.Location.Filename})"); } chromeProviderNode.Value.Nodes.RemoveAll(n => n.Key != "Inherits"); @@ -197,7 +197,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules chromeProviderNode.Value.Value = ""; if (!ExtractPanelDefinition(chromeProviderNode, regionsNode)) - panelLocations.Add("{0} ({1})".F(chromeProviderNode.Key, chromeProviderNode.Location.Filename)); + panelLocations.Add($"{chromeProviderNode.Key} ({chromeProviderNode.Location.Filename})"); if (regionsNode.Value.Nodes.Any()) chromeProviderNode.AddNode(regionsNode); diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RemoveWithPermanentInjury.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RemoveWithPermanentInjury.cs index ed49b96da8..d3e518ef05 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RemoveWithPermanentInjury.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RemoveWithPermanentInjury.cs @@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules public override IEnumerable UpdateActorNode(ModData modData, MiniYamlNode actorNode) { if (actorNode.RemoveNodes("WithPermanentInjury") > 0) - locations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); yield break; } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RenameSpins.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RenameSpins.cs index 54ee7522fa..115bc35622 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RenameSpins.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200202/RenameSpins.cs @@ -45,7 +45,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules fallsToEarth.AddNode("MaximumSpinSpeed", "0"); fallsToEarth.RemoveNode(spinsNode); - locations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); } } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/AddPipDecorationTraits.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/AddPipDecorationTraits.cs index 60ad7bc3bc..57910930dd 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/AddPipDecorationTraits.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/AddPipDecorationTraits.cs @@ -58,13 +58,13 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules yield return "Some passenger types define custom cargo pips. Review the following definitions:\n" + UpdateUtils.FormatMessageList(cargoPipLocations) + "\nand, if required, add the following to the WithCargoPipsDecoration traits:\n" + - "CustomPipSequences:\n" + cargoCustomPips.Select(p => "\t{0}: {1}".F(p, PipReplacements[p])).JoinWith("\n"); + "CustomPipSequences:\n" + cargoCustomPips.Select(p => $"\t{p}: {PipReplacements[p]}").JoinWith("\n"); if (harvesterCustomPips.Any() && harvesterPipLocations.Any()) yield return "Review the following definitions:\n" + UpdateUtils.FormatMessageList(harvesterPipLocations) + "\nand, if required, add the following to the WithHarvesterPipsDecoration traits:\n" + - "ResourceSequences:\n" + harvesterCustomPips.Select(kv => "\t{0}: {1}".F(kv.Key, PipReplacements[kv.Value])).JoinWith("\n"); + "ResourceSequences:\n" + harvesterCustomPips.Select(kv => $"\t{kv.Key}: {PipReplacements[kv.Value]}").JoinWith("\n"); customPips = false; locations.Clear(); @@ -124,7 +124,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules } addNodes.Add(ammoPips); - locations.Add("{0}: {1} ({2})".F(actorNode.Key, ammoPips.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {ammoPips.Key} ({actorNode.Location.Filename})"); } foreach (var cargo in actorNode.ChildrenMatching("Cargo")) @@ -154,8 +154,8 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules continue; addNodes.Add(cargoPips); - locations.Add("{0}: {1} ({2})".F(actorNode.Key, cargoPips.Key, actorNode.Location.Filename)); - cargoPipLocations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {cargoPips.Key} ({actorNode.Location.Filename})"); + cargoPipLocations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); } foreach (var passenger in actorNode.ChildrenMatching("Passenger")) @@ -199,8 +199,8 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules harvesterPips.AddNode("PipCount", 7); addNodes.Add(harvesterPips); - locations.Add("{0}: {1} ({2})".F(actorNode.Key, harvesterPips.Key, actorNode.Location.Filename)); - harvesterPipLocations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {harvesterPips.Key} ({actorNode.Location.Filename})"); + harvesterPipLocations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); } foreach (var resourceType in actorNode.ChildrenMatching("ResourceType")) @@ -254,7 +254,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules storagePips.AddNode("FullSequence", PipReplacements["yellow"]); addNodes.Add(storagePips); - locations.Add("{0}: {1} ({2})".F(actorNode.Key, storagePips.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {storagePips.Key} ({actorNode.Location.Filename})"); } foreach (var addNode in addNodes) diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ConvertSupportPowerRangesToFootprint.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ConvertSupportPowerRangesToFootprint.cs index 3b763d66ef..5e6af3a6d1 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ConvertSupportPowerRangesToFootprint.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ConvertSupportPowerRangesToFootprint.cs @@ -42,7 +42,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { range = rangeNode.NodeValue(); if (range > 3) - locations.Add("{0} ({1})".F(rangeNode.Key, rangeNode.Location.Filename)); + locations.Add($"{rangeNode.Key} ({rangeNode.Location.Filename})"); power.RemoveNode(rangeNode); } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/CreateFlashPaletteEffectWarhead.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/CreateFlashPaletteEffectWarhead.cs index 1851ce433a..0b6d73fd25 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/CreateFlashPaletteEffectWarhead.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/CreateFlashPaletteEffectWarhead.cs @@ -35,7 +35,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules var weaponName = weaponNode.Value.Value; - weaponsToUpdate.Add(new Tuple(weaponName, traitName, "{0} ({1})".F(actorNode.Key, actorNode.Location.Filename))); + weaponsToUpdate.Add(new Tuple(weaponName, traitName, $"{actorNode.Key} ({actorNode.Location.Filename})")); nukePowerTrait.RemoveNodes("FlashType"); } @@ -47,7 +47,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { if (weaponsToUpdate.Any()) yield return "Add a FlashPaletteEffectWarhead to the following weapons:\n" + - UpdateUtils.FormatMessageList(weaponsToUpdate.Select(x => "Weapon `{0}`, used by trait `{1}` on actor {2}".F(x.Item1, x.Item2, x.Item3))); + UpdateUtils.FormatMessageList(weaponsToUpdate.Select(x => $"Weapon `{x.Item1}`, used by trait `{x.Item2}` on actor {x.Item3}")); weaponsToUpdate.Clear(); } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ModernizeDecorationTraits.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ModernizeDecorationTraits.cs index 129091c54c..da05f78840 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ModernizeDecorationTraits.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/ModernizeDecorationTraits.cs @@ -66,7 +66,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules public override IEnumerable UpdateActorNode(ModData modData, MiniYamlNode actorNode) { - var locationKey = "{0} ({1})".F(actorNode.Key, actorNode.Location.Filename); + var locationKey = $"{actorNode.Key} ({actorNode.Location.Filename})"; foreach (var trait in LegacyDecorationTraits) { diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/MoveClassicFacingFudge.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/MoveClassicFacingFudge.cs index fbeec73ca4..fb3d6a5a27 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/MoveClassicFacingFudge.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/MoveClassicFacingFudge.cs @@ -54,7 +54,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules if (usesClassicFacings) { bo.RenameKey("ClassicFacingBodyOrientation"); - locations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); } } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveLaysTerrain.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveLaysTerrain.cs index dd41d731a5..fe96caaad6 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveLaysTerrain.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveLaysTerrain.cs @@ -22,7 +22,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules public override IEnumerable UpdateActorNode(ModData modData, MiniYamlNode actorNode) { if (actorNode.RemoveNodes("LaysTerrain") > 0) - yield return "'LaysTerrain' was removed from {0} ({1}) without replacement.\n".F(actorNode.Key, actorNode.Location.Filename); + yield return $"'LaysTerrain' was removed from {actorNode.Key} ({actorNode.Location.Filename}) without replacement.\n"; yield break; } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveMuzzleSplitFacings.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveMuzzleSplitFacings.cs index de14497b91..332c3982ac 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveMuzzleSplitFacings.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/RemoveMuzzleSplitFacings.cs @@ -33,9 +33,10 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules var sequence = sequenceNode.Value.Value; var facings = muzzleSplitFacings.NodeValue() - 1; var actor = actorNode.Key.ToLowerInvariant(); - yield return "The Armament muzzle effect has been removed from {0} ({1}).\n".F(actor, actorNode.Location.Filename) + - "If you would like to restore the muzzle effect you must redefine `MuzzleSequence: {0}`\n".F(sequence) + - "and replace the {0}0-{1} sequence definitions with a single `{0}` sequence that uses\n".F(sequence, facings) + + yield return + $"The Armament muzzle effect has been removed from {actor} ({actorNode.Location.Filename}).\n" + + $"If you would like to restore the muzzle effect you must redefine `MuzzleSequence: {sequence}`\n" + + $"and replace the {sequence}0-{facings} sequence definitions with a single `{sequence}` sequence that uses\n" + "the Combine syntax to assemble the different facing sprites."; a.RemoveNode(muzzleSplitFacings); diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/SplitDamagedByTerrain.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/SplitDamagedByTerrain.cs index f0982e61d4..3ec78f022d 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/SplitDamagedByTerrain.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/SplitDamagedByTerrain.cs @@ -24,9 +24,9 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules foreach (var damaged in actorNode.ChildrenMatching("DamagedByTerrain", includeRemovals: false)) { if (damaged.RemoveNodes("DamageThreshold") > 0) - yield return "'DamageThreshold' was removed from {0} ({1}) without replacement.\n".F(actorNode.Key, actorNode.Location.Filename); + yield return $"'DamageThreshold' was removed from {actorNode.Key} ({actorNode.Location.Filename}) without replacement.\n"; if (damaged.RemoveNodes("StartOnThreshold") > 0) - yield return "'StartOnThreshold' was removed from {0} ({1}) without replacement.\n".F(actorNode.Key, actorNode.Location.Filename); + yield return $"'StartOnThreshold' was removed from {actorNode.Key} ({actorNode.Location.Filename}) without replacement.\n"; } yield break; diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/UpdateMapInits.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/UpdateMapInits.cs index 3b8a6f55d6..96fef3cc58 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20200503/UpdateMapInits.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20200503/UpdateMapInits.cs @@ -36,10 +36,10 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules public override IEnumerable UpdateMapActorNode(ModData modData, MiniYamlNode actorNode) { if (actorNode.RemoveNodes("Plugs") > 0) - yield return "Initial plugs for actor {0} will need to be reconfigured using the map editor.".F(actorNode.Key); + yield return $"Initial plugs for actor {actorNode.Key} will need to be reconfigured using the map editor."; if (actorNode.RemoveNodes("TurretFacings") > 0) - yield return "Initial turret facings for actor {0} will need to be reconfigured using the map editor.".F(actorNode.Key); + yield return $"Initial turret facings for actor {actorNode.Key} will need to be reconfigured using the map editor."; var bodyFacing = WAngle.Zero; foreach (var facing in actorNode.ChildrenMatching("Facing")) diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemovePlaceBuildingPalette.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemovePlaceBuildingPalette.cs index a72853f8f2..18b7e16acc 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemovePlaceBuildingPalette.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemovePlaceBuildingPalette.cs @@ -64,7 +64,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules } if (removed > 0) - locations.Add("{0} ({1})".F(actorNode.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key} ({actorNode.Location.Filename})"); yield break; } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveRenderSpritesScale.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveRenderSpritesScale.cs index de90451b54..bc8ba6e83c 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveRenderSpritesScale.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveRenderSpritesScale.cs @@ -23,8 +23,8 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { foreach (var renderSprites in actorNode.ChildrenMatching("RenderSprites")) if (renderSprites.RemoveNodes("Scale") > 0) - yield return "The actor-level scaling has been removed from {0} ({1}).\n".F(actorNode.Key, actorNode.Location.Filename) + - "You must manually define Scale on its sequences instead."; + yield return $"The actor-level scaling has been removed from {actorNode.Key} ({actorNode.Location.Filename}).\n" + + "You must manually define Scale on its sequences instead."; } } } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveSmokeTrailWhenDamaged.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveSmokeTrailWhenDamaged.cs index 0a25bad053..d8ac35a633 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveSmokeTrailWhenDamaged.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/RemoveSmokeTrailWhenDamaged.cs @@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules public override IEnumerable UpdateActorNode(ModData modData, MiniYamlNode actorNode) { - var locationKey = "{0} ({1})".F(actorNode.Key, actorNode.Location.Filename); + var locationKey = $"{actorNode.Key} ({actorNode.Location.Filename})"; var anyConditionalSmokeTrail = false; foreach (var smokeTrail in actorNode.ChildrenMatching("SmokeTrailWhenDamaged")) diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceShadowPalette.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceShadowPalette.cs index 45d9eefd8d..9f250e5cf6 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceShadowPalette.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceShadowPalette.cs @@ -38,7 +38,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { foreach (var projectileNode in weaponNode.ChildrenMatching("Projectile")) if (projectileNode.RemoveNodes("ShadowPalette") > 0) - locations.Add("{0}: {1} ({2})".F(weaponNode.Key, weaponNode.Key, weaponNode.Location.Filename)); + locations.Add($"{weaponNode.Key}: {weaponNode.Key} ({weaponNode.Location.Filename})"); yield break; } @@ -47,11 +47,11 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { foreach (var node in actorNode.ChildrenMatching("WithShadow")) if (node.RemoveNodes("Palette") > 0) - locations.Add("{0}: {1} ({2})".F(actorNode.Key, node.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {node.Key} ({actorNode.Location.Filename})"); foreach (var node in actorNode.ChildrenMatching("WithParachute")) if (node.RemoveNodes("ShadowPalette") > 0) - locations.Add("{0}: {1} ({2})".F(actorNode.Key, node.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {node.Key} ({actorNode.Location.Filename})"); yield break; } diff --git a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceWithColoredOverlayPalette.cs b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceWithColoredOverlayPalette.cs index 6d5e8e7376..6bb5cdbe24 100644 --- a/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceWithColoredOverlayPalette.cs +++ b/OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceWithColoredOverlayPalette.cs @@ -35,7 +35,7 @@ namespace OpenRA.Mods.Common.UpdateRules.Rules { foreach (var node in actorNode.ChildrenMatching("WithColoredOverlay")) if (node.RemoveNodes("Palette") > 0) - locations.Add("{0}: {1} ({2})".F(actorNode.Key, node.Key, actorNode.Location.Filename)); + locations.Add($"{actorNode.Key}: {node.Key} ({actorNode.Location.Filename})"); yield break; } diff --git a/OpenRA.Mods.Common/UpdateRules/UpdateUtils.cs b/OpenRA.Mods.Common/UpdateRules/UpdateUtils.cs index 45d93ec225..e2cdebbf3a 100644 --- a/OpenRA.Mods.Common/UpdateRules/UpdateUtils.cs +++ b/OpenRA.Mods.Common/UpdateRules/UpdateUtils.cs @@ -254,7 +254,7 @@ namespace OpenRA.Mods.Common.UpdateRules public static string FormatMessageList(IEnumerable messages, int indent = 0, string separator = "*") { var prefix = string.Concat(Enumerable.Repeat(" ", indent)); - return string.Join("\n", messages.Select(m => prefix + " {0} {1}".F(separator, m.Replace("\n", "\n " + prefix)))); + return string.Join("\n", messages.Select(m => prefix + $" {separator} {m.Replace("\n", "\n " + prefix)}")); } } diff --git a/OpenRA.Mods.Common/Util.cs b/OpenRA.Mods.Common/Util.cs index 5728993932..6872863ada 100644 --- a/OpenRA.Mods.Common/Util.cs +++ b/OpenRA.Mods.Common/Util.cs @@ -212,19 +212,22 @@ namespace OpenRA.Mods.Common public static string FriendlyTypeName(Type t) { if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(HashSet<>)) - return "Set of {0}".F(t.GetGenericArguments().Select(FriendlyTypeName).ToArray()); + return $"Set of {t.GetGenericArguments().Select(FriendlyTypeName).ToArray()}"; if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>)) - return "Mapping of {0} to {1}".F(t.GetGenericArguments().Select(FriendlyTypeName).ToArray()); + { + var args = t.GetGenericArguments().Select(FriendlyTypeName).ToArray(); + return $"Dictionary with Key: {args[0]}, Value {args[1]}"; + } if (t.IsSubclassOf(typeof(Array))) - return "Collection of {0}".F(FriendlyTypeName(t.GetElementType())); + return $"Collection of {FriendlyTypeName(t.GetElementType())}"; if (t.IsGenericType && t.GetGenericTypeDefinition().GetInterfaces().Any(e => e.IsGenericType && e.GetGenericTypeDefinition() == typeof(IEnumerable<>))) - return "Collection of {0}".F(FriendlyTypeName(t.GetGenericArguments().First())); + return $"Collection of {FriendlyTypeName(t.GetGenericArguments().First())}"; if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) - return "{0} (optional)".F(t.GetGenericArguments().Select(FriendlyTypeName).First()); + return $"{t.GetGenericArguments().Select(FriendlyTypeName).First()} (optional)"; if (t == typeof(int) || t == typeof(uint)) return "Integer"; diff --git a/OpenRA.Mods.Common/UtilityCommands/CheckConditionalTraitInterfaceOverrides.cs b/OpenRA.Mods.Common/UtilityCommands/CheckConditionalTraitInterfaceOverrides.cs index 2d6a16ad75..4274fe8140 100644 --- a/OpenRA.Mods.Common/UtilityCommands/CheckConditionalTraitInterfaceOverrides.cs +++ b/OpenRA.Mods.Common/UtilityCommands/CheckConditionalTraitInterfaceOverrides.cs @@ -52,7 +52,7 @@ namespace OpenRA.Mods.Common.UtilityCommands if (!IsConditionalTrait(t)) continue; - var overridesCreated = t.GetMethod("{0}.{1}".F(interfaceType.FullName, methodName), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) != null; + var overridesCreated = t.GetMethod($"{interfaceType.FullName}.{methodName}", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) != null; if (overridesCreated) { Console.WriteLine("{0} must override ConditionalTrait's {1} method instead of implementing {2} directly", t.Name, methodName, interfaceType.Name); diff --git a/OpenRA.Mods.Common/UtilityCommands/CheckMissingSprites.cs b/OpenRA.Mods.Common/UtilityCommands/CheckMissingSprites.cs index f9ad97f723..dfeb570e45 100644 --- a/OpenRA.Mods.Common/UtilityCommands/CheckMissingSprites.cs +++ b/OpenRA.Mods.Common/UtilityCommands/CheckMissingSprites.cs @@ -68,12 +68,12 @@ namespace OpenRA.Mods.Common.UtilityCommands { // The stacktrace associated with yaml errors are not very useful // Suppress them to make the lint output less intimidating for modders - Console.WriteLine("\t{0}".F(e.Message)); + Console.WriteLine($"\t{e.Message}"); failed = true; } catch (Exception e) { - Console.WriteLine("Failed with exception: {0}".F(e)); + Console.WriteLine($"Failed with exception: {e}"); failed = true; } } @@ -82,7 +82,7 @@ namespace OpenRA.Mods.Common.UtilityCommands { // The stacktrace associated with yaml errors are not very useful // Suppress them to make the lint output less intimidating for modders - Console.WriteLine("{0}".F(e.Message)); + Console.WriteLine($"{e.Message}"); failed = true; } diff --git a/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs b/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs index 853ab975b5..a24372c507 100644 --- a/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs +++ b/OpenRA.Mods.Common/UtilityCommands/CheckYaml.cs @@ -52,13 +52,13 @@ namespace OpenRA.Mods.Common.UtilityCommands Log.AddChannel("perf", null); // bind some nonfatal error handling into FieldLoader, so we don't just *explode*. - ObjectCreator.MissingTypeAction = s => EmitError("Missing Type: {0}".F(s)); - FieldLoader.UnknownFieldAction = (s, f) => EmitError("FieldLoader: Missing field `{0}` on `{1}`".F(s, f.Name)); + ObjectCreator.MissingTypeAction = s => EmitError($"Missing Type: {s}"); + FieldLoader.UnknownFieldAction = (s, f) => EmitError($"FieldLoader: Missing field `{s}` on `{f.Name}`"); var maps = new List(); if (args.Length < 2) { - Console.WriteLine("Testing mod: {0}".F(modData.Manifest.Metadata.Title)); + Console.WriteLine($"Testing mod: {modData.Manifest.Metadata.Title}"); // Run all rule checks on the default mod rules. CheckRules(modData, modData.DefaultRules); @@ -73,7 +73,7 @@ namespace OpenRA.Mods.Common.UtilityCommands } catch (Exception e) { - EmitError("{0} failed with exception: {1}".F(customPassType, e)); + EmitError($"{customPassType} failed with exception: {e}"); } } @@ -85,7 +85,7 @@ namespace OpenRA.Mods.Common.UtilityCommands foreach (var testMap in maps) { - Console.WriteLine("Testing map: {0}".F(testMap.Title)); + Console.WriteLine($"Testing map: {testMap.Title}"); // Lint tests can't be trusted if the map rules are bogus // so report that problem then skip the tests @@ -109,7 +109,7 @@ namespace OpenRA.Mods.Common.UtilityCommands } catch (Exception e) { - EmitError("{0} failed with exception: {1}".F(customMapPassType, e)); + EmitError($"{customMapPassType} failed with exception: {e}"); } } } @@ -122,7 +122,7 @@ namespace OpenRA.Mods.Common.UtilityCommands } catch (Exception e) { - EmitError("Failed with exception: {0}".F(e)); + EmitError($"Failed with exception: {e}"); Environment.Exit(1); } } @@ -138,7 +138,7 @@ namespace OpenRA.Mods.Common.UtilityCommands } catch (Exception e) { - EmitError("{0} failed with exception: {1}".F(customRulesPassType, e)); + EmitError($"{customRulesPassType} failed with exception: {e}"); } } } diff --git a/OpenRA.Mods.Common/UtilityCommands/ConvertSpriteToPngCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ConvertSpriteToPngCommand.cs index 1be9ae6926..4a616e08a8 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ConvertSpriteToPngCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ConvertSpriteToPngCommand.cs @@ -79,7 +79,7 @@ namespace OpenRA.Mods.Common.UtilityCommands } var png = new Png(pngData, SpriteFrameType.Indexed8, frameSize.Width, frameSize.Height, palColors); - png.Save("{0}-{1:D4}.png".F(prefix, count++)); + png.Save($"{prefix}-{(count++):D4}.png"); } Console.WriteLine("Saved {0}-[0..{1}].png", prefix, count - 1); diff --git a/OpenRA.Mods.Common/UtilityCommands/CreateManPage.cs b/OpenRA.Mods.Common/UtilityCommands/CreateManPage.cs index 1eadb8789d..924a906fc8 100644 --- a/OpenRA.Mods.Common/UtilityCommands/CreateManPage.cs +++ b/OpenRA.Mods.Common/UtilityCommands/CreateManPage.cs @@ -49,10 +49,10 @@ namespace OpenRA.Mods.Common.UtilityCommands Console.WriteLine(".TP"); - Console.Write(".BR {0}.{1}=".F(section.Key, field.Name)); + Console.Write($".BR {section.Key}.{field.Name}="); var value = field.GetValue(section.Value); if (value != null && !value.ToString().StartsWith("System.", StringComparison.Ordinal)) - Console.WriteLine("\\fI{0}\\fR".F(value)); + Console.WriteLine($"\\fI{value}\\fR"); else Console.WriteLine(); diff --git a/OpenRA.Mods.Common/UtilityCommands/DebugChromeRegions.cs b/OpenRA.Mods.Common/UtilityCommands/DebugChromeRegions.cs index 886a445c77..26a0e76ca7 100644 --- a/OpenRA.Mods.Common/UtilityCommands/DebugChromeRegions.cs +++ b/OpenRA.Mods.Common/UtilityCommands/DebugChromeRegions.cs @@ -63,14 +63,14 @@ namespace OpenRA.Mods.Common.UtilityCommands { var r = s.Bounds; if (c.Value.PanelSides.HasSide(s.PanelSides)) - regions.Add("[\"{0}.<{1}>\",{2},{3},{4},{5}]".F(c.Key, s.PanelSides, r.X, r.Y, r.Width, r.Height)); + regions.Add($"[\"{c.Key}.<{s.PanelSides}>\",{r.X},{r.Y},{r.Width},{r.Height}]"); } } foreach (var kv in c.Value.Regions) { var r = kv.Value; - regions.Add("[\"{0}\",{1},{2},{3},{4}]".F(c.Key + "." + kv.Key, r.X, r.Y, r.Width, r.Height)); + regions.Add($"[\"{c.Key}.{kv.Key}\",{r.X},{r.Y},{r.Width},{r.Height}]"); } } diff --git a/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs b/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs index 6b03cea2a3..14bfb38078 100644 --- a/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/DumpSequenceSheetsCommand.cs @@ -39,7 +39,7 @@ namespace OpenRA.Mods.Common.UtilityCommands if (mapPackage != null) sequences = new Map(modData, mapPackage).Rules.Sequences; else if (!modData.DefaultSequences.TryGetValue(args[2], out sequences)) - throw new InvalidOperationException("{0} is not a valid tileset or map path".F(args[2])); + throw new InvalidOperationException($"{args[2]} is not a valid tileset or map path"); sequences.Preload(); @@ -50,12 +50,12 @@ namespace OpenRA.Mods.Common.UtilityCommands { var max = s == sb.Current ? (int)sb.CurrentChannel + 1 : 4; for (var i = 0; i < max; i++) - s.AsPng((TextureChannel)ChannelMasks[i], palette).Save("{0}.png".F(count++)); + s.AsPng((TextureChannel)ChannelMasks[i], palette).Save($"{count++}.png"); } sb = sequences.SpriteCache.SheetBuilders[SheetType.BGRA]; foreach (var s in sb.AllSheets) - s.AsPng().Save("{0}.png".F(count++)); + s.AsPng().Save($"{count++}.png"); Console.WriteLine("Saved [0..{0}].png", count - 1); } diff --git a/OpenRA.Mods.Common/UtilityCommands/ExtractFilesCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ExtractFilesCommand.cs index c870bbdbc2..cd0a67ecf2 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ExtractFilesCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ExtractFilesCommand.cs @@ -33,7 +33,7 @@ namespace OpenRA.Mods.Common.UtilityCommands { var src = utility.ModData.DefaultFileSystem.Open(f); if (src == null) - throw new InvalidOperationException("File not found: {0}".F(f)); + throw new InvalidOperationException($"File not found: {f}"); var data = src.ReadAllBytes(); File.WriteAllBytes(f, data); Console.WriteLine(f + " saved."); diff --git a/OpenRA.Mods.Common/UtilityCommands/ExtractLuaDocsCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ExtractLuaDocsCommand.cs index ba176173ef..220e3c322b 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ExtractLuaDocsCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ExtractLuaDocsCommand.cs @@ -75,7 +75,7 @@ namespace OpenRA.Mods.Common.UtilityCommands foreach (var m in members.OrderBy(m => m.Name)) { var desc = m.HasAttribute() ? m.GetCustomAttributes(true).First().Lines.JoinWith("\n") : ""; - Console.WriteLine("{0}{1}".F(m.LuaDocString(), desc)); + Console.WriteLine($"{m.LuaDocString()}{desc}"); } Console.WriteLine(""); @@ -119,7 +119,7 @@ namespace OpenRA.Mods.Common.UtilityCommands Console.WriteLine("
"); if (hasRequires) - Console.WriteLine("Requires {1}: {0}".F(required.JoinWith(", "), required.Length == 1 ? "Trait" : "Traits")); + Console.WriteLine($"Requires {(required.Length == 1 ? "Trait" : "Traits")}: {required.JoinWith(", ")}"); Console.WriteLine(""); } @@ -165,7 +165,7 @@ namespace OpenRA.Mods.Common.UtilityCommands Console.WriteLine("
"); if (hasRequires) - Console.WriteLine("Requires {1}: {0}".F(required.JoinWith(", "), required.Length == 1 ? "Trait" : "Traits")); + Console.WriteLine($"Requires {(required.Length == 1 ? "Trait" : "Traits")}: {required.JoinWith(", ")}"); Console.WriteLine(""); } diff --git a/OpenRA.Mods.Common/UtilityCommands/ExtractTraitDocsCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ExtractTraitDocsCommand.cs index 6e847aaa33..47a76777a7 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ExtractTraitDocsCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ExtractTraitDocsCommand.cs @@ -53,13 +53,13 @@ namespace OpenRA.Mods.Common.UtilityCommands { currentNamespace = t.Namespace; doc.AppendLine(); - doc.AppendLine("## {0}".F(currentNamespace)); + doc.AppendLine($"## {currentNamespace}"); } var traitName = t.Name.EndsWith("Info") ? t.Name.Substring(0, t.Name.Length - 4) : t.Name; var traitDescLines = t.GetCustomAttributes(false).SelectMany(d => d.Lines); doc.AppendLine(); - doc.AppendLine("### {0}".F(traitName)); + doc.AppendLine($"### {traitName}"); foreach (var line in traitDescLines) doc.AppendLine(line); @@ -70,14 +70,14 @@ namespace OpenRA.Mods.Common.UtilityCommands if (t.HasAttribute()) doc.AppendLine(); - doc.Append("Requires trait{0}: ".F(reqCount > 1 ? "s" : "")); + doc.Append($"Requires trait{(reqCount > 1 ? "s" : "")}: "); var i = 0; foreach (var require in requires) { var n = require.Name; var name = n.EndsWith("Info") ? n.Remove(n.Length - 4, 4) : n; - doc.Append("[`{0}`](#{1}){2}".F(name, name.ToLowerInvariant(), i + 1 == reqCount ? ".\n" : ", ")); + doc.Append($"[`{name}`](#{name.ToLowerInvariant()}){(i + 1 == reqCount ? ".\n" : ", ")}"); i++; } } @@ -94,7 +94,7 @@ namespace OpenRA.Mods.Common.UtilityCommands var fieldType = Util.FriendlyTypeName(info.Field.FieldType); var loadInfo = info.Field.GetCustomAttributes(true).FirstOrDefault(); var defaultValue = loadInfo != null && loadInfo.Required ? "(required)" : FieldSaver.SaveField(liveTraitInfo, info.Field.Name).Value.Value; - doc.Append("{0}{1}{2}".F(info.YamlName, defaultValue, fieldType)); + doc.Append($"{info.YamlName}{defaultValue}{fieldType}"); doc.Append(""); foreach (var line in fieldDescLines) doc.Append(line + " "); diff --git a/OpenRA.Mods.Common/UtilityCommands/ExtractWeaponDocsCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ExtractWeaponDocsCommand.cs index 1ddfa70517..aa64c5b975 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ExtractWeaponDocsCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ExtractWeaponDocsCommand.cs @@ -63,12 +63,12 @@ namespace OpenRA.Mods.Common.UtilityCommands { currentNamespace = t.Namespace; doc.AppendLine(); - doc.AppendLine("## {0}".F(currentNamespace)); + doc.AppendLine($"## {currentNamespace}"); } var traitName = t.Name.EndsWith("Info") ? t.Name.Substring(0, t.Name.Length - 4) : t.Name; doc.AppendLine(); - doc.AppendLine("### {0}".F(traitName)); + doc.AppendLine($"### {traitName}"); var traitDescLines = t.GetCustomAttributes(false).SelectMany(d => d.Lines); foreach (var line in traitDescLines) @@ -87,7 +87,7 @@ namespace OpenRA.Mods.Common.UtilityCommands var fieldDescLines = info.Field.GetCustomAttributes(true).SelectMany(d => d.Lines); var fieldType = Util.FriendlyTypeName(info.Field.FieldType); var defaultValue = liveTraitInfo == null ? "" : FieldSaver.SaveField(liveTraitInfo, info.Field.Name).Value.Value; - doc.Append("{0}{1}{2}".F(info.YamlName, defaultValue, fieldType)); + doc.Append($"{info.YamlName}{defaultValue}{fieldType}"); doc.Append(""); foreach (var line in fieldDescLines) diff --git a/OpenRA.Mods.Common/UtilityCommands/ExtractZeroBraneStudioLuaAPI.cs b/OpenRA.Mods.Common/UtilityCommands/ExtractZeroBraneStudioLuaAPI.cs index 432d14e30c..3d37bdba49 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ExtractZeroBraneStudioLuaAPI.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ExtractZeroBraneStudioLuaAPI.cs @@ -136,7 +136,7 @@ namespace OpenRA.Mods.Common.UtilityCommands Console.WriteLine(" name = \"OpenRA\","); Console.WriteLine(" description = \"Adds API description for auto-complete and tooltip support for OpenRA.\","); Console.WriteLine(" author = \"Matthias Mailänder\","); - Console.WriteLine(" version = \"{0}\",".F(Game.ModData.Manifest.Metadata.Version.Split('-').LastOrDefault())); + Console.WriteLine($" version = \"{Game.ModData.Manifest.Metadata.Version.Split('-').LastOrDefault()}\","); Console.WriteLine(); Console.WriteLine(" onRegister = function(self)"); Console.WriteLine(" ide:AddAPI(\"lua\", \"openra\", api)"); diff --git a/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs index a14691fd9c..fd6fa1d0cc 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ImportLegacyMapCommand.cs @@ -67,7 +67,7 @@ namespace OpenRA.Mods.Common.UtilityCommands // The original game isn't case sensitive, but we are. var tileset = GetTileset(mapSection).ToUpperInvariant(); if (!ModData.DefaultTerrainInfo.TryGetValue(tileset, out var terrainInfo)) - throw new InvalidDataException("Unknown tileset {0}".F(tileset)); + throw new InvalidDataException($"Unknown tileset {tileset}"); Map = new Map(ModData, terrainInfo, MapSize, MapSize) { @@ -299,8 +299,8 @@ namespace OpenRA.Mods.Common.UtilityCommands var parts = s.Value.Split(','); var loc = Exts.ParseIntegerInvariant(parts[1]); var type = parts[0].ToLowerInvariant(); - var key = "{0},{1}".F(loc % MapSize, loc / MapSize); - var value = "{0},{1}".F(type, parts[2]); + var key = $"{loc % MapSize},{loc / MapSize}"; + var value = $"{type},{parts[2]}"; var node = new MiniYamlNode(key, value); if (type.StartsWith("sc")) scorches.Add(node); @@ -422,13 +422,13 @@ namespace OpenRA.Mods.Common.UtilityCommands var actorCount = map.ActorDefinitions.Count; if (!map.Rules.Actors.ContainsKey(parts[1].ToLowerInvariant())) - Console.WriteLine("Ignoring unknown actor type: `{0}`".F(parts[1].ToLowerInvariant())); + Console.WriteLine($"Ignoring unknown actor type: `{parts[1].ToLowerInvariant()}`"); else map.ActorDefinitions.Add(new MiniYamlNode("Actor" + actorCount++, actor.Save())); } catch (Exception) { - Console.WriteLine("Malformed actor definition: `{0}`".F(s)); + Console.WriteLine($"Malformed actor definition: `{s}`"); } } } diff --git a/OpenRA.Mods.Common/UtilityCommands/ReplayMetadataCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ReplayMetadataCommand.cs index 5a508e207f..1edeebeb57 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ReplayMetadataCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ReplayMetadataCommand.cs @@ -41,7 +41,7 @@ namespace OpenRA.Mods.Common.UtilityCommands var playerCount = 0; foreach (var p in info.Players) { - var playerLines = FieldSaver.Save(p).ToLines("{0}".F(playerCount++)); + var playerLines = FieldSaver.Save(p).ToLines($"{playerCount++}"); foreach (var line in playerLines) Console.WriteLine("\t\t" + line); } diff --git a/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs b/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs index ed09fc3691..4d1bcf8127 100644 --- a/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs +++ b/OpenRA.Mods.Common/UtilityCommands/ResizeMapCommand.cs @@ -63,7 +63,7 @@ namespace OpenRA.Mods.Common.UtilityCommands if (!map.Contains(locationInit.Value)) { - Console.WriteLine("Removing actor {0} located at {1} due being outside of the new map boundaries.".F(actor.Type, locationInit.Value)); + Console.WriteLine($"Removing actor {actor.Type} located at {locationInit.Value} due being outside of the new map boundaries."); forRemoval.Add(kv); } } diff --git a/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs b/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs index 760d8032bc..ee6f1e021e 100644 --- a/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/FireClusterWarhead.cs @@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.Warheads public void RulesetLoaded(Ruleset rules, WeaponInfo info) { if (!rules.Weapons.TryGetValue(Weapon.ToLowerInvariant(), out weapon)) - throw new YamlException("Weapons Ruleset does not contain an entry '{0}'".F(Weapon.ToLowerInvariant())); + throw new YamlException($"Weapons Ruleset does not contain an entry '{Weapon.ToLowerInvariant()}'"); } public override void DoImpact(in Target target, WarheadArgs args) diff --git a/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs b/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs index c3ec4ac2c3..e12eacade0 100644 --- a/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs +++ b/OpenRA.Mods.Common/Warheads/LeaveSmudgeWarhead.cs @@ -64,7 +64,7 @@ namespace OpenRA.Mods.Common.Warheads continue; if (!smudgeLayers.TryGetValue(smudgeType, out var smudgeLayer)) - throw new NotImplementedException("Unknown smudge type `{0}`".F(smudgeType)); + throw new NotImplementedException($"Unknown smudge type `{smudgeType}`"); smudgeLayer.AddSmudge(sc); } diff --git a/OpenRA.Mods.Common/Widgets/ImageWidget.cs b/OpenRA.Mods.Common/Widgets/ImageWidget.cs index 0e47bf6170..6b10e39df6 100644 --- a/OpenRA.Mods.Common/Widgets/ImageWidget.cs +++ b/OpenRA.Mods.Common/Widgets/ImageWidget.cs @@ -65,7 +65,7 @@ namespace OpenRA.Mods.Common.Widgets var sprite = ChromeProvider.GetImage(collection, name); if (sprite == null) - throw new ArgumentException("Sprite {0}/{1} was not found.".F(collection, name)); + throw new ArgumentException($"Sprite {collection}/{name} was not found."); WidgetUtils.DrawRGBA(sprite, RenderOrigin); } diff --git a/OpenRA.Mods.Common/Widgets/LabelWidget.cs b/OpenRA.Mods.Common/Widgets/LabelWidget.cs index 4af8ff97f6..75fec1a846 100644 --- a/OpenRA.Mods.Common/Widgets/LabelWidget.cs +++ b/OpenRA.Mods.Common/Widgets/LabelWidget.cs @@ -68,7 +68,7 @@ namespace OpenRA.Mods.Common.Widgets public override void Draw() { if (!Game.Renderer.Fonts.TryGetValue(Font, out var font)) - throw new ArgumentException("Requested font '{0}' was not found.".F(Font)); + throw new ArgumentException($"Requested font '{Font}' was not found."); var text = GetText(); if (text == null) diff --git a/OpenRA.Mods.Common/Widgets/Logic/AssetBrowserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/AssetBrowserLogic.cs index ef83c18ba2..ef09faac73 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/AssetBrowserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/AssetBrowserLogic.cs @@ -149,9 +149,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (frameText != null) { frameText.GetText = () => - isVideoLoaded ? - "{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) : - "{0} / {1}".F(currentFrame, currentSprites.Length - 1); + isVideoLoaded ? $"{player.Video.CurrentFrame + 1} / {player.Video.Frames}" + : $"{currentFrame} / {currentSprites.Length - 1}"; } var playButton = panel.GetOrNull("BUTTON_PLAY"); diff --git a/OpenRA.Mods.Common/Widgets/Logic/ButtonTooltipLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/ButtonTooltipLogic.cs index a2d0ea049e..5c29d04570 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ButtonTooltipLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ButtonTooltipLogic.cs @@ -34,7 +34,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var hotkey = widget.Get("HOTKEY"); hotkey.Visible = true; - var hotkeyLabel = "({0})".F(key.DisplayString()); + var hotkeyLabel = $"({key.DisplayString()})"; hotkey.GetText = () => hotkeyLabel; hotkey.Bounds.X = labelWidth + 2 * label.Bounds.X; diff --git a/OpenRA.Mods.Common/Widgets/Logic/ColorPickerLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/ColorPickerLogic.cs index a267616424..209e2dee12 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ColorPickerLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ColorPickerLogic.cs @@ -103,13 +103,13 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (logicArgs.TryGetValue("PaletteColumns", out var yaml)) if (!int.TryParse(yaml.Value, out paletteCols)) - throw new YamlException("Invalid value for PaletteColumns: {0}".F(yaml.Value)); + throw new YamlException($"Invalid value for PaletteColumns: {yaml.Value}"); if (logicArgs.TryGetValue("PalettePresetRows", out yaml)) if (!int.TryParse(yaml.Value, out palettePresetRows)) - throw new YamlException("Invalid value for PalettePresetRows: {0}".F(yaml.Value)); + throw new YamlException($"Invalid value for PalettePresetRows: {yaml.Value}"); if (logicArgs.TryGetValue("PaletteCustomRows", out yaml)) if (!int.TryParse(yaml.Value, out paletteCustomRows)) - throw new YamlException("Invalid value for PaletteCustomRows: {0}".F(yaml.Value)); + throw new YamlException($"Invalid value for PaletteCustomRows: {yaml.Value}"); for (var j = 0; j < palettePresetRows; j++) { diff --git a/OpenRA.Mods.Common/Widgets/Logic/ConnectionLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/ConnectionLogic.cs index f4ce82517d..0952837591 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ConnectionLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ConnectionLogic.cs @@ -59,8 +59,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var panel = widget; panel.Get("ABORT_BUTTON").OnClick = () => { CloseWindow(); onAbort(); }; - widget.Get("CONNECTING_DESC").GetText = () => - "Connecting to {0}...".F(endpoint); + widget.Get("CONNECTING_DESC").GetText = () => $"Connecting to {endpoint}..."; } public static void Connect(ConnectionTarget endpoint, string password, Action onConnect, Action onAbort) @@ -102,8 +101,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic onRetry(password); }; - widget.Get("CONNECTING_DESC").GetText = () => - "Could not connect to {0}".F(orderManager.Endpoint); + widget.Get("CONNECTING_DESC").GetText = () => $"Could not connect to {orderManager.Endpoint}"; var connectionError = widget.Get("CONNECTION_ERROR"); connectionError.GetText = () => orderManager.ServerError ?? orderManager.Connection.ErrorMessage ?? "Unknown error"; @@ -163,7 +161,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic switchButton.OnClick = () => { - var launchCommand = "Launch.URI={0}".F(new UriBuilder("tcp", orderManager.Connection.EndPoint.Address.ToString(), orderManager.Connection.EndPoint.Port)); + var launchCommand = $"Launch.URI={new UriBuilder("tcp", orderManager.Connection.EndPoint.Address.ToString(), orderManager.Connection.EndPoint.Port)}"; Game.SwitchToExternalMod(orderManager.ServerExternalMod, new[] { launchCommand }, () => { orderManager.ServerError = "Failed to switch mod."; diff --git a/OpenRA.Mods.Common/Widgets/Logic/DirectConnectLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/DirectConnectLogic.cs index 593888dceb..5d7731ffbf 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/DirectConnectLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/DirectConnectLogic.cs @@ -43,7 +43,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var port = Exts.WithDefault(1234, () => Exts.ParseIntegerInvariant(portField.Text)); - Game.Settings.Player.LastServer = "{0}:{1}".F(ipField.Text, port); + Game.Settings.Player.LastServer = $"{ipField.Text}:{port}"; Game.Settings.Save(); ConnectionLogic.Connect(new ConnectionTarget(ipField.Text, port), "", () => { Ui.CloseWindow(); openLobby(); }, DoNothing); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Editor/ActorEditLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Editor/ActorEditLogic.cs index b839839d77..5d646e5e5c 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Editor/ActorEditLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Editor/ActorEditLogic.cs @@ -461,7 +461,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic actorId = actor.ID; this.actor = actor; this.handles = handles; - Text = "Edited {0} ({1})".F(actor.Info.Name, actor.ID); + Text = $"Edited {actor.Info.Name} ({actor.ID})"; } public void Execute() diff --git a/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs index 295abdc640..b8ce525ca5 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Editor/MapEditorLogic.cs @@ -66,8 +66,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos); var map = worldRenderer.World.Map; - return map.Height.Contains(cell) ? - "{0},{1} ({2})".F(cell, map.Height[cell], map.Tiles[cell].Type) : ""; + return map.Height.Contains(cell) ? $"{cell},{map.Height[cell]} ({map.Tiles[cell].Type})" : ""; }; } @@ -76,7 +75,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var reslayer = worldRenderer.World.WorldActor.TraitsImplementing().FirstOrDefault(); if (reslayer != null) - cashLabel.GetText = () => "$ {0}".F(reslayer.NetWorth); + cashLabel.GetText = () => $"$ {reslayer.NetWorth}"; } var undoButton = widget.GetOrNull("UNDO_BUTTON"); diff --git a/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs index e15273dc87..c54f08b6fc 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/GameSaveBrowserLogic.cs @@ -69,7 +69,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (!File.Exists(Path.Combine(baseSavePath, defaultSaveFilename + ".orasav"))) break; - defaultSaveFilename = world.Map.Title + " ({0})".F(++filenameAttempt); + defaultSaveFilename = world.Map.Title + $" ({++filenameAttempt})"; } var saveButton = panel.Get("SAVE_BUTTON"); @@ -132,7 +132,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { ConfirmationDialogs.ButtonPrompt( title: "Delete selected game save?", - text: "Delete '{0}'?".F(Path.GetFileNameWithoutExtension(selectedSave)), + text: $"Delete '{Path.GetFileNameWithoutExtension(selectedSave)}'?", onConfirm: () => { Delete(selectedSave); @@ -155,7 +155,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { ConfirmationDialogs.ButtonPrompt( title: "Delete all game saves?", - text: "Delete {0} game saves?".F(games.Count), + text: $"Delete {games.Count} game saves?", onConfirm: () => { foreach (var s in games.ToList()) @@ -295,7 +295,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var orders = new List() { Order.FromTargetString("LoadGameSave", Path.GetFileName(selectedSave), true), - Order.Command("state {0}".F(Session.ClientState.Ready)) + Order.Command($"state {Session.ClientState.Ready}") }; Game.CreateAndStartLocalServer(map.Uid, orders); @@ -322,7 +322,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { ConfirmationDialogs.ButtonPrompt( title: "Overwrite save game?", - text: "Overwrite {0}?".F(saveTextField.Text), + text: $"Overwrite {saveTextField.Text}?", onConfirm: inner, confirmText: "Overwrite", onCancel: () => { }); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs index cb4825b1c9..e1c9996402 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/DebugLogic.cs @@ -31,7 +31,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic.Ingame var cell = worldRenderer.Viewport.ViewToWorld(Viewport.LastMousePos); var map = worldRenderer.World.Map; var wpos = map.CenterOfCell(cell); - return map.Height.Contains(cell) ? "({0},{1}) ({2})".F(cell, map.Height[cell], wpos) : ""; + return map.Height.Contains(cell) ? $"({cell},{map.Height[cell]}) ({wpos})" : ""; }); labelWidget.GetText = () => cellPosText.Update(Viewport.LastMousePos); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoStatsLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoStatsLogic.cs index 67c0e2a08c..6e86d7e159 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoStatsLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameInfoStatsLogic.cs @@ -76,7 +76,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (teams.Count() > 1) { var teamHeader = ScrollItemWidget.Setup(teamTemplate, () => true, () => { }); - teamHeader.Get("TEAM").GetText = () => t.Key == 0 ? "No Team" : "Team {0}".F(t.Key); + teamHeader.Get("TEAM").GetText = () => t.Key == 0 ? "No Team" : $"Team {t.Key}"; var teamRating = teamHeader.Get("TEAM_SCORE"); var scoreCache = new CachedTransform(s => s.ToString()); var teamMemberScores = t.Select(tt => tt.PlayerStatistics).Where(s => s != null).ToArray().Select(s => s.Experience); @@ -101,7 +101,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (player == null || player.RelationshipWith(pp) == PlayerRelationship.Ally || player.WinState != WinState.Undefined) { flag.GetImageName = () => pp.Faction.InternalName; - var factionName = pp.Faction.Name != pp.DisplayFaction.Name ? "{0} ({1})".F(pp.DisplayFaction.Name, pp.Faction.Name) : pp.Faction.Name; + var factionName = pp.Faction.Name != pp.DisplayFaction.Name ? $"{pp.DisplayFaction.Name} ({pp.Faction.Name})" : pp.Faction.Name; item.Get("FACTION").GetText = () => factionName; } else @@ -149,11 +149,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic { hideMenu(true); ConfirmationDialogs.ButtonPrompt( - title: "Kick {0}?".F(client.Name), + title: $"Kick {client.Name}?", text: "They will not be able to rejoin this game.", onConfirm: () => { - orderManager.IssueOrder(Order.Command("kick {0} {1}".F(client.Index, false))); + orderManager.IssueOrder(Order.Command($"kick {client.Index} {false}")); hideMenu(false); }, onCancel: () => hideMenu(false), diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameTimerLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameTimerLogic.cs index aa19337758..7070187b02 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameTimerLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/GameTimerLogic.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (world.ReplayTimestep == 1) return "Max Speed"; - return "{0}% Speed".F(world.Timestep * 100 / world.ReplayTimestep); + return $"{world.Timestep * 100 / world.ReplayTimestep}% Speed"; }; if (timer != null) @@ -64,9 +64,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var connection = orderManager.Connection as ReplayConnection; if (connection != null && connection.FinalGameTick != 0) - timerTooltip.GetTooltipText = () => "{0}% complete".F(world.WorldTick * 100 / connection.FinalGameTick); + timerTooltip.GetTooltipText = () => $"{world.WorldTick * 100 / connection.FinalGameTick}% complete"; else if (connection != null && connection.TickCount != 0) - timerTooltip.GetTooltipText = () => "{0}% complete".F(orderManager.NetFrameNumber * 100 / connection.TickCount); + timerTooltip.GetTooltipText = () => $"{orderManager.NetFrameNumber * 100 / connection.TickCount}% complete"; else timerTooltip.GetTooltipText = null; } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameCashCounterLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameCashCounterLogic.cs index e61ef3fe6b..9474b77cfe 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameCashCounterLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/IngameCashCounterLogic.cs @@ -42,7 +42,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic displayLabel = cashLabel.F(displayResources); cash.GetText = () => displayLabel; - cash.GetTooltipText = () => "Silo Usage: {0}/{1}".F(playerResources.Resources, playerResources.ResourceCapacity); + cash.GetTooltipText = () => $"Silo Usage: {playerResources.Resources}/{playerResources.ResourceCapacity}"; } public override void Tick() diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs index 3d43851293..c1381f1fea 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ObserverShroudSelectorLogic.cs @@ -99,7 +99,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var noTeams = teams.Count() == 1; foreach (var t in teams) { - var label = noTeams ? "Players" : t.Key == 0 ? "No Team" : "Team {0}".F(t.Key); + var label = noTeams ? "Players" : t.Key == 0 ? "No Team" : $"Team {t.Key}"; groups.Add(label, t); } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ProductionTooltipLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ProductionTooltipLogic.cs index e03fed79cf..49dc66927e 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/ProductionTooltipLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/ProductionTooltipLogic.cs @@ -87,7 +87,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (hotkeyLabel.Visible) { - var hotkeyText = "({0})".F(hotkey.DisplayString()); + var hotkeyText = $"({hotkey.DisplayString()})"; hotkeyWidth = font.Measure(hotkeyText).X + 2 * nameLabel.Bounds.X; hotkeyLabel.Text = hotkeyText; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Ingame/SupportPowerTooltipLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Ingame/SupportPowerTooltipLogic.cs index 3197432e38..ce58768286 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Ingame/SupportPowerTooltipLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Ingame/SupportPowerTooltipLogic.cs @@ -64,7 +64,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var remaining = WidgetUtils.FormatTime(sp.RemainingTicks, world.Timestep); var total = WidgetUtils.FormatTime(sp.Info.ChargeInterval, world.Timestep); - timeLabel.Text = "{0} / {1}".F(remaining, total); + timeLabel.Text = $"{remaining} / {total}"; } else timeLabel.Text = customLabel; @@ -74,7 +74,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic hotkeyLabel.Visible = hotkey.IsValid(); if (hotkeyLabel.Visible) { - var hotkeyText = "({0})".F(hotkey.DisplayString()); + var hotkeyText = $"({hotkey.DisplayString()})"; hotkeyWidth = hotkeyFont.Measure(hotkeyText).X + 2 * nameLabel.Bounds.X; hotkeyLabel.Text = hotkeyText; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Installation/DownloadPackageLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Installation/DownloadPackageLogic.cs index bdf9451a82..7062e56b13 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Installation/DownloadPackageLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Installation/DownloadPackageLogic.cs @@ -49,7 +49,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var status = new CachedTransform(s => WidgetUtils.TruncateText(s, statusLabel.Bounds.Width, statusFont)); statusLabel.GetText = () => status.Update(getStatusText()); - var text = "Downloading {0}".F(download.Title); + var text = $"Downloading {download.Title}"; panel.Get("TITLE").Text = text; ShowDownloadDialog(); @@ -78,7 +78,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic dataReceived = read / (float)(1L << (mag * 10)); dataSuffix = SizeSuffixes[mag]; - getStatusText = () => "Downloading from {2} {0:0.00} {1}".F(dataReceived, dataSuffix, downloadHost ?? "unknown host"); + getStatusText = () => $"Downloading from {downloadHost ?? "unknown host"} {dataReceived:0.00} {dataSuffix}"; progressBar.Indeterminate = true; } else @@ -88,7 +88,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic dataReceived = read / (float)(1L << (mag * 10)); dataSuffix = SizeSuffixes[mag]; - getStatusText = () => "Downloading from {4} {1:0.00}/{2:0.00} {3} ({0}%)".F(progressPercentage, dataReceived, dataTotal, dataSuffix, downloadHost ?? "unknown host"); + getStatusText = () => $"Downloading from {downloadHost ?? "unknown host"} {dataReceived:0.00}/{dataTotal:0.00} {dataSuffix} ({progressPercentage}%)"; progressBar.Indeterminate = false; } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromDiscLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromDiscLogic.cs index 8069e5054c..0838385506 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromDiscLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Installation/InstallFromDiscLogic.cs @@ -219,7 +219,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic continue; } - Log.Write("install", "Copying {0} -> {1}".F(sourcePath, targetPath)); + Log.Write("install", $"Copying {sourcePath} -> {targetPath}"); extracted.Add(targetPath); Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); @@ -233,7 +233,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (length < ShowPercentageThreshold) message = "Copying " + displayFilename; else - onProgress = b => message = "Copying " + displayFilename + " ({0}%)".F(100 * b / length); + onProgress = b => message = $"Copying {displayFilename} ({100 * b / length}%)"; CopyStream(source, target, length, onProgress); } @@ -362,11 +362,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (length < ShowPercentageThreshold) updateMessage("Extracting " + displayFilename); else - onProgress = b => updateMessage("Extracting " + displayFilename + " ({0}%)".F(100 * b / length)); + onProgress = b => updateMessage($"Extracting {displayFilename} ({100 * b / length}%)"); using (var target = File.OpenWrite(targetPath)) { - Log.Write("install", "Extracting {0} -> {1}".F(sourcePath, targetPath)); + Log.Write("install", $"Extracting {sourcePath} -> {targetPath}"); if (type == ExtractionType.Blast) Blast.Decompress(source, target, (read, _) => onProgress?.Invoke(read)); else @@ -398,9 +398,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); using (var target = File.OpenWrite(targetPath)) { - Log.Write("install", "Extracting {0} -> {1}".F(sourcePath, targetPath)); + Log.Write("install", $"Extracting {sourcePath} -> {targetPath}"); var displayFilename = Path.GetFileName(Path.GetFileName(targetPath)); - Action onProgress = percent => updateMessage("Extracting {0} ({1}%)".F(displayFilename, percent)); + Action onProgress = percent => updateMessage($"Extracting {displayFilename} ({percent}%)"); reader.ExtractFile(node.Value.Value, target, onProgress); } } @@ -447,9 +447,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); using (var target = File.OpenWrite(targetPath)) { - Log.Write("install", "Extracting {0} -> {1}".F(sourcePath, targetPath)); + Log.Write("install", $"Extracting {sourcePath} -> {targetPath}"); var displayFilename = Path.GetFileName(Path.GetFileName(targetPath)); - Action onProgress = percent => updateMessage("Extracting {0} ({1}%)".F(displayFilename, percent)); + Action onProgress = percent => updateMessage($"Extracting {displayFilename} ({percent}%)"); reader.ExtractFile(node.Value.Value, target, onProgress); } } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Installation/ModContentPromptLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Installation/ModContentPromptLogic.cs index ceb1f77ba7..533cbdfceb 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Installation/ModContentPromptLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Installation/ModContentPromptLogic.cs @@ -73,7 +73,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var download = downloadYaml.FirstOrDefault(n => n.Key == content.QuickDownload); if (download == null) - throw new InvalidOperationException("Mod QuickDownload `{0}` definition not found.".F(content.QuickDownload)); + throw new InvalidOperationException($"Mod QuickDownload `{content.QuickDownload}` definition not found."); Ui.OpenWindow("PACKAGE_DOWNLOAD_PANEL", new WidgetArgs { diff --git a/OpenRA.Mods.Common/Widgets/Logic/IntroductionPromptLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/IntroductionPromptLogic.cs index f811127828..9ab404d339 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/IntroductionPromptLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/IntroductionPromptLogic.cs @@ -113,7 +113,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic battlefieldCameraDropDown.GetText = () => battlefieldCameraLabel.Update(ds.ViewportDistance); var uiScaleDropdown = widget.Get("UI_SCALE_DROPDOWN"); - var uiScaleLabel = new CachedTransform(s => "{0}%".F((int)(100 * s))); + var uiScaleLabel = new CachedTransform(s => $"{(int)(100 * s)}%"); uiScaleDropdown.OnMouseDown = _ => DisplaySettingsLogic.ShowUIScaleDropdown(uiScaleDropdown, ds); uiScaleDropdown.GetText = () => uiScaleLabel.Update(ds.UIScale); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickClientLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickClientLogic.cs index cdfbed503e..cacd8d9c24 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickClientLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickClientLogic.cs @@ -19,7 +19,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic [ObjectCreator.UseCtor] public KickClientLogic(Widget widget, string clientName, Action okPressed, Action cancelPressed) { - widget.Get("TITLE").GetText = () => "Kick {0}?".F(clientName); + widget.Get("TITLE").GetText = () => $"Kick {clientName}?"; var tempBan = false; var preventRejoiningCheckbox = widget.Get("PREVENT_REJOINING_CHECKBOX"); diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickSpectatorsLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickSpectatorsLogic.cs index 336f2edcfd..fbd58a1a93 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickSpectatorsLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/KickSpectatorsLogic.cs @@ -19,7 +19,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic [ObjectCreator.UseCtor] public KickSpectatorsLogic(Widget widget, string clientCount, Action okPressed, Action cancelPressed) { - widget.Get("TEXT").GetText = () => "Are you sure you want to kick {0} spectators?".F(clientCount); + widget.Get("TEXT").GetText = () => $"Are you sure you want to kick {clientCount} spectators?"; widget.Get("OK_BUTTON").OnClick = () => { diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyLogic.cs index 4bfc6fed3a..4197214e63 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyLogic.cs @@ -229,7 +229,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var bot = botTypes.Random(Game.CosmeticRandom); var c = orderManager.LobbyInfo.ClientInSlot(slot.Key); if (slot.Value.AllowBots == true && (c == null || c.Bot != null)) - orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot.Key, botController.Index, bot))); + orderManager.IssueOrder(Order.Command($"slot_bot {slot.Key} {botController.Index} {bot}")); } } } @@ -261,9 +261,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var teamOptions = Enumerable.Range(2, teamCount - 1).Reverse().Select(d => new DropDownOption { - Title = "{0} Teams".F(d), + Title = $"{d} Teams", IsSelected = () => false, - OnClick = () => orderManager.IssueOrder(Order.Command("assignteams {0}".F(d.ToString()))) + OnClick = () => orderManager.IssueOrder(Order.Command($"assignteams {d.ToString()}")) }).ToList(); if (orderManager.LobbyInfo.Slots.Any(s => s.Value.AllowBots)) @@ -518,7 +518,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (map.Status == MapStatus.Available) { // Tell the server that we have the map - orderManager.IssueOrder(Order.Command("state {0}".F(Session.ClientState.NotReady))); + orderManager.IssueOrder(Order.Command($"state {Session.ClientState.NotReady}")); if (addBotOnMapLoad) { @@ -526,7 +526,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var bot = map.PlayerActorInfo.TraitInfos().Select(t => t.Type).FirstOrDefault(); var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin); if (slot != null && bot != null) - orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot, botController.Index, bot))); + orderManager.IssueOrder(Order.Command($"slot_bot {slot} {botController.Index} {bot}")); addBotOnMapLoad = false; } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyOptionsLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyOptionsLogic.cs index fb181fa976..89a114a329 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyOptionsLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyOptionsLogic.cs @@ -107,7 +107,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic checkbox.IsChecked = () => optionValue.Update(orderManager.LobbyInfo.GlobalSettings).IsEnabled; checkbox.IsDisabled = () => configurationDisabled() || optionValue.Update(orderManager.LobbyInfo.GlobalSettings).IsLocked; checkbox.OnClick = () => orderManager.IssueOrder(Order.Command( - "option {0} {1}".F(option.Id, !optionValue.Update(orderManager.LobbyInfo.GlobalSettings).IsEnabled))); + $"option {option.Id} {!optionValue.Update(orderManager.LobbyInfo.GlobalSettings).IsEnabled}")); } foreach (var option in allOptions.Where(o => !(o is LobbyBooleanOption))) @@ -148,7 +148,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic Func, ScrollItemWidget, ScrollItemWidget> setupItem = (c, template) => { Func isSelected = () => optionValue.Update(orderManager.LobbyInfo.GlobalSettings).Value == c.Key; - Action onClick = () => orderManager.IssueOrder(Order.Command("option {0} {1}".F(option.Id, c.Key))); + Action onClick = () => orderManager.IssueOrder(Order.Command($"option {option.Id} {c.Key}")); var item = ScrollItemWidget.Setup(template, isSelected, onClick); item.Get("LABEL").GetText = () => c.Value; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyUtils.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyUtils.cs index 787e4332c1..9219c21a5c 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyUtils.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/LobbyUtils.cs @@ -57,7 +57,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin); bots.Add(new SlotDropDownOption(b.Name, - "slot_bot {0} {1} {2}".F(slot.PlayerReference, botController.Index, b.Type), + $"slot_bot {slot.PlayerReference} {botController.Index} {b.Type}", () => client != null && client.Bot == b.Type)); } } @@ -79,7 +79,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic public static void ShowPlayerActionDropDown(DropDownButtonWidget dropdown, Session.Slot slot, Session.Client c, OrderManager orderManager, Widget lobby, Action before, Action after) { - Action okPressed = tempBan => { orderManager.IssueOrder(Order.Command("kick {0} {1}".F(c.Index, tempBan))); after(); }; + Action okPressed = tempBan => { orderManager.IssueOrder(Order.Command($"kick {c.Index} {tempBan}")); after(); }; var onClick = new Action(() => { before(); @@ -106,7 +106,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic options.Add(new DropDownOption { Title = "Transfer Admin", - OnClick = () => orderManager.IssueOrder(Order.Command("make_admin {0}".F(c.Index))) + OnClick = () => orderManager.IssueOrder(Order.Command($"make_admin {c.Index}")) }); } @@ -115,7 +115,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic options.Add(new DropDownOption { Title = "Move to Spectator", - OnClick = () => orderManager.IssueOrder(Order.Command("make_spectator {0}".F(c.Index))) + OnClick = () => orderManager.IssueOrder(Order.Command($"make_spectator {c.Index}")) }); } @@ -137,7 +137,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var item = ScrollItemWidget.Setup(itemTemplate, () => client.Team == ii, - () => orderManager.IssueOrder(Order.Command("team {0} {1}".F(client.Index, ii)))); + () => orderManager.IssueOrder(Order.Command($"team {client.Index} {ii}"))); item.Get("LABEL").GetText = () => ii == 0 ? "-" : ii.ToString(); return item; }; @@ -153,9 +153,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var item = ScrollItemWidget.Setup(itemTemplate, () => client.Handicap == ii, - () => orderManager.IssueOrder(Order.Command("handicap {0} {1}".F(client.Index, ii)))); + () => orderManager.IssueOrder(Order.Command($"handicap {client.Index} {ii}"))); - var label = "{0}%".F(ii); + var label = $"{ii}%"; item.Get("LABEL").GetText = () => label; return item; }; @@ -199,7 +199,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var item = ScrollItemWidget.Setup(itemTemplate, () => client.Faction == factionId, - () => orderManager.IssueOrder(Order.Command("faction {0} {1}".F(client.Index, factionId)))); + () => orderManager.IssueOrder(Order.Command($"faction {client.Index} {factionId}"))); var faction = factions[factionId]; item.Get("LABEL").GetText = () => faction.Name; var flag = item.Get("FLAG"); @@ -231,7 +231,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic } color.RemovePanel(); - orderManager.IssueOrder(Order.Command("color {0} {1}".F(client.Index, preview.Color))); + orderManager.IssueOrder(Order.Command($"color {client.Index} {preview.Color}")); }; Action onChange = c => preview.Color = c; @@ -271,7 +271,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var selectedSpawn = DetermineSelectedSpawnPoint(mapPreview, preview, mi); if (Game.IsHost || orderManager.LobbyInfo.Clients.FirstOrDefault(cc => cc.SpawnPoint == selectedSpawn) == orderManager.LocalClient) - orderManager.IssueOrder(Order.Command("clear_spawn {0}".F(selectedSpawn))); + orderManager.IssueOrder(Order.Command($"clear_spawn {selectedSpawn}")); } static int DetermineSelectedSpawnPoint(MapPreviewWidget mapPreview, MapPreview preview, MouseInput mi) @@ -289,7 +289,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == selectedSpawnPoint) || orderManager.LobbyInfo.DisabledSpawnPoints.Contains(selectedSpawnPoint); if (selectedSpawnPoint == 0 || !owned) - orderManager.IssueOrder(Order.Command("spawn {0} {1}".F((playerToMove ?? orderManager.LocalClient).Index, selectedSpawnPoint))); + orderManager.IssueOrder(Order.Command($"spawn {(playerToMove ?? orderManager.LocalClient).Index} {selectedSpawnPoint}")); } public static List AvailableSpawnPoints(int spawnPoints, Session lobbyInfo) @@ -492,11 +492,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic Action okPressed = () => { - orderManager.IssueOrder(Order.Command("allow_spectators {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowSpectators))); + orderManager.IssueOrder(Order.Command($"allow_spectators {!orderManager.LobbyInfo.GlobalSettings.AllowSpectators}")); orderManager.IssueOrders( orderManager.LobbyInfo.Clients.Where( c => c.IsObserver && !c.IsAdmin).Select( - client => Order.Command("kick {0} {1}".F(client.Index, client.Name))).ToArray()); + client => Order.Command($"kick {client.Index} {client.Name}")).ToArray()); after(); }; @@ -510,14 +510,14 @@ namespace OpenRA.Mods.Common.Widgets.Logic { Game.LoadWidget(null, "KICK_SPECTATORS_DIALOG", lobby.Get("TOP_PANELS_ROOT"), new WidgetArgs { - { "clientCount", "{0}".F(spectatorCount) }, + { "clientCount", $"{spectatorCount}" }, { "okPressed", okPressed }, { "cancelPressed", after } }); } else { - orderManager.IssueOrder(Order.Command("allow_spectators {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowSpectators))); + orderManager.IssueOrder(Order.Command($"allow_spectators {!orderManager.LobbyInfo.GlobalSettings.AllowSpectators}")); after(); } }; @@ -588,7 +588,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic dropdown.IsDisabled = () => s.LockTeam || orderManager.LocalClient.IsReady; dropdown.OnMouseDown = _ => ShowHandicapDropDown(dropdown, c, orderManager); - var handicapLabel = new CachedTransform(h => "{0}%".F(h)); + var handicapLabel = new CachedTransform(h => $"{h}%"); dropdown.GetText = () => handicapLabel.Update(c.Handicap); HideChildWidget(parent, "HANDICAP"); @@ -599,7 +599,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var team = parent.Get("HANDICAP"); team.IsVisible = () => true; - var handicapLabel = new CachedTransform(h => "{0}%".F(h)); + var handicapLabel = new CachedTransform(h => $"{h}%"); team.GetText = () => handicapLabel.Update(c.Handicap); HideChildWidget(parent, "HANDICAP_DROPDOWN"); } @@ -638,7 +638,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic status.IsDisabled = () => c.Bot != null || map.Status != MapStatus.Available || !isEnabled; var state = orderManager.LocalClient.IsReady ? Session.ClientState.NotReady : Session.ClientState.Ready; - status.OnClick = () => orderManager.IssueOrder(Order.Command("state {0}".F(state))); + status.OnClick = () => orderManager.IssueOrder(Order.Command($"state {state}")); } public static void SetupReadyWidget(Widget parent, Session.Slot s, Session.Client c) @@ -662,7 +662,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var font = Game.Renderer.Fonts[nameLabel.Font]; var nameSize = font.Measure(nameText); - timeLabel.GetText = () => "{0:D2}:{1:D2}".F(time.Hour, time.Minute); + timeLabel.GetText = () => $"{time.Hour:D2}:{time.Minute:D2}"; nameLabel.GetColor = () => nameColor; nameLabel.GetText = () => nameText; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/MapPreviewLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/MapPreviewLogic.cs index af40e21cf7..106c7870ff 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/MapPreviewLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/MapPreviewLogic.cs @@ -82,7 +82,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic getMap().Map.Install(mapRepository, () => { if (orderManager != null) - Game.RunAfterTick(() => orderManager.IssueOrder(Order.Command("state {0}".F(Session.ClientState.NotReady)))); + Game.RunAfterTick(() => orderManager.IssueOrder(Order.Command($"state {Session.ClientState.NotReady}"))); }); }; @@ -138,9 +138,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic // Server does not provide the total file length if (map.DownloadPercentage == 0) - return "Downloading {0} kB".F(map.DownloadBytes / 1024); + return $"Downloading {map.DownloadBytes / 1024} kB"; - return "Downloading {0} kB ({1}%)".F(map.DownloadBytes / 1024, map.DownloadPercentage); + return $"Downloading {map.DownloadBytes / 1024} kB ({map.DownloadPercentage}%)"; }; } @@ -161,7 +161,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic map.Install(mapRepository, () => { if (orderManager != null) - Game.RunAfterTick(() => orderManager.IssueOrder(Order.Command("state {0}".F(Session.ClientState.NotReady)))); + Game.RunAfterTick(() => orderManager.IssueOrder(Order.Command($"state {Session.ClientState.NotReady}"))); }); } else if (map.Status == MapStatus.Unavailable) @@ -226,7 +226,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var font = Game.Renderer.Fonts[authorLabel.Font]; var author = new CachedTransform( - m => WidgetUtils.TruncateText("Created by {0}".F(m.Author), authorLabel.Bounds.Width, font)); + m => WidgetUtils.TruncateText($"Created by {m.Author}", authorLabel.Bounds.Width, font)); authorLabel.GetText = () => author.Update(getMap().Map); } } diff --git a/OpenRA.Mods.Common/Widgets/Logic/Lobby/SpawnSelectorTooltipLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Lobby/SpawnSelectorTooltipLogic.cs index 2114898d80..a6b1ad2893 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Lobby/SpawnSelectorTooltipLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Lobby/SpawnSelectorTooltipLogic.cs @@ -75,7 +75,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic flag.IsVisible = () => playerFaction != null; flag.GetImageCollection = () => "flags"; flag.GetImageName = () => playerFaction; - team.GetText = () => "Team {0}".F(playerTeam); + team.GetText = () => $"Team {playerTeam}"; team.IsVisible = () => playerTeam > 0; } } diff --git a/OpenRA.Mods.Common/Widgets/Logic/MainMenuLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/MainMenuLogic.cs index e3a1feb48d..052ed301bd 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/MainMenuLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/MainMenuLogic.cs @@ -313,7 +313,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { Game.RunAfterTick(() => // run on the main thread { - SetNewsStatus("Failed to retrieve news: {0}".F(e)); + SetNewsStatus($"Failed to retrieve news: {e}"); }); } }); @@ -388,7 +388,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic } catch (Exception ex) { - SetNewsStatus("Failed to parse news: {0}".F(ex.Message)); + SetNewsStatus($"Failed to parse news: {ex.Message}"); } return null; diff --git a/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs index 06b46b4a24..29aeba1099 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/MapChooserLogic.cs @@ -193,7 +193,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic // 'all game types' extra item categories.Insert(0, (null as string, tabMaps[tab].Count())); - Func<(string Category, int Count), string> showItem = x => "{0} ({1})".F(x.Category ?? "All Maps", x.Count); + Func<(string Category, int Count), string> showItem = x => $"{x.Category ?? "All Maps"} ({x.Count})"; Func<(string Category, int Count), ScrollItemWidget, ScrollItemWidget> setupItem = (ii, template) => { @@ -272,7 +272,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (type != null) details = type + " "; - details += "({0} players)".F(preview.PlayerCount); + details += $"({preview.PlayerCount} players)"; detailsWidget.GetText = () => details; } @@ -280,7 +280,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (authorWidget != null) { var font = Game.Renderer.Fonts[authorWidget.Font]; - var author = WidgetUtils.TruncateText("Created by {0}".F(preview.Author), authorWidget.Bounds.Width, font); + var author = WidgetUtils.TruncateText($"Created by {preview.Author}", authorWidget.Bounds.Width, font); authorWidget.GetText = () => author; } @@ -331,7 +331,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { ConfirmationDialogs.ButtonPrompt( title: "Delete map", - text: "Delete the map '{0}'?".F(modData.MapCache[map].Title), + text: $"Delete the map '{modData.MapCache[map].Title}'?", onConfirm: () => { var newUid = DeleteMap(map); diff --git a/OpenRA.Mods.Common/Widgets/Logic/MissionBrowserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/MissionBrowserLogic.cs index 6cb28130b0..5edd328bac 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/MissionBrowserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/MissionBrowserLogic.cs @@ -372,10 +372,10 @@ namespace OpenRA.Mods.Common.Widgets.Logic var orders = new List(); if (difficulty != null) - orders.Add(Order.Command("option difficulty {0}".F(difficulty))); + orders.Add(Order.Command($"option difficulty {difficulty}")); - orders.Add(Order.Command("option gamespeed {0}".F(gameSpeed))); - orders.Add(Order.Command("state {0}".F(Session.ClientState.Ready))); + orders.Add(Order.Command($"option gamespeed {gameSpeed}")); + orders.Add(Order.Command($"state {Session.ClientState.Ready}")); var missionData = selectedMap.WorldActorInfo.TraitInfoOrDefault(); if (missionData != null && missionData.StartVideo != null && modData.DefaultFileSystem.Exists(missionData.StartVideo)) diff --git a/OpenRA.Mods.Common/Widgets/Logic/MusicPlayerLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/MusicPlayerLogic.cs index aaacb45908..a0520a4375 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/MusicPlayerLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/MusicPlayerLogic.cs @@ -92,7 +92,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var totalMinutes = currentSong.Length / 60; var totalSeconds = currentSong.Length % 60; - return "{0:D2}:{1:D2} / {2:D2}:{3:D2}".F(minutes, seconds, totalMinutes, totalSeconds); + return $"{minutes:D2}:{seconds:D2} / {totalMinutes:D2}:{totalSeconds:D2}"; }; var musicTitle = panel.GetOrNull("TITLE_LABEL"); @@ -157,7 +157,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic static string SongLengthLabel(MusicInfo song) { - return "{0:D1}:{1:D2}".F(song.Length / 60, song.Length % 60); + return $"{song.Length / 60:D1}:{song.Length % 60:D2}"; } } } diff --git a/OpenRA.Mods.Common/Widgets/Logic/PerfDebugLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/PerfDebugLogic.cs index 9f879e2ecb..85fff281ec 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/PerfDebugLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/PerfDebugLogic.cs @@ -40,10 +40,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic fpsReferenceFrame = Game.RenderFrame; } - return "FPS: {0}\nTick {1} @ {2:F1} ms\nRender {3} @ {4:F1} ms\nBatches: {5}".F( - fps, Game.LocalTick, PerfHistory.Items["tick_time"].Average(Game.Settings.Debug.Samples), - Game.RenderFrame, PerfHistory.Items["render"].Average(Game.Settings.Debug.Samples), - PerfHistory.Items["batches"].LastValue); + return $"FPS: {fps}\nTick {Game.LocalTick} @ {PerfHistory.Items["tick_time"].Average(Game.Settings.Debug.Samples):F1} ms\nRender {Game.RenderFrame} @ {PerfHistory.Items["render"].Average(Game.Settings.Debug.Samples):F1} ms\nBatches: {PerfHistory.Items["batches"].LastValue}"; }; } } diff --git a/OpenRA.Mods.Common/Widgets/Logic/ReplayBrowserLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/ReplayBrowserLogic.cs index ebfc057dab..6a194c4557 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ReplayBrowserLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ReplayBrowserLogic.cs @@ -102,7 +102,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic }); var replayDuration = new CachedTransform(r => - "Duration: {0}".F(WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds))); + $"Duration: {WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds)}"); panel.Get("DURATION").GetText = () => replayDuration.Update(selectedReplay); SetupFilters(); @@ -424,7 +424,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { ConfirmationDialogs.ButtonPrompt( title: "Delete selected replay?", - text: "Delete replay '{0}'?".F(Path.GetFileNameWithoutExtension(r.FilePath)), + text: $"Delete replay '{Path.GetFileNameWithoutExtension(r.FilePath)}'?", onConfirm: () => { DeleteReplay(r); @@ -461,7 +461,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic ConfirmationDialogs.ButtonPrompt( title: "Delete all selected replays?", - text: "Delete {0} replays?".F(list.Count), + text: $"Delete {list.Count} replays?", onConfirm: () => { list.ForEach(DeleteReplay); @@ -635,7 +635,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var noTeams = players.Count() == 1; foreach (var p in players) { - var label = noTeams ? "Players" : p.Key == 0 ? "No Team" : "Team {0}".F(p.Key); + var label = noTeams ? "Players" : p.Key == 0 ? "No Team" : $"Team {p.Key}"; teams.Add(label, p); } diff --git a/OpenRA.Mods.Common/Widgets/Logic/ReplayUtils.cs b/OpenRA.Mods.Common/Widgets/Logic/ReplayUtils.cs index f5e9a0597a..69fd2afb74 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ReplayUtils.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ReplayUtils.cs @@ -52,7 +52,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic static bool IncompatibleReplayDialog(string type, string name, Action onCancel) { var error = "It was recorded with an " + type; - error += string.IsNullOrEmpty(name) ? "." : ":\n{0}".F(name); + error += string.IsNullOrEmpty(name) ? "." : $":\n{name}"; ConfirmationDialogs.ButtonPrompt("Incompatible Replay", error, onCancel: onCancel); diff --git a/OpenRA.Mods.Common/Widgets/Logic/ServerCreationLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/ServerCreationLogic.cs index f085afc051..9d842412d1 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ServerCreationLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ServerCreationLogic.cs @@ -78,7 +78,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var font = Game.Renderer.Fonts[authorLabel.Font]; var author = new CachedTransform( - m => WidgetUtils.TruncateText("Created by {0}".F(m.Author), authorLabel.Bounds.Width, font)); + m => WidgetUtils.TruncateText($"Created by {m.Author}", authorLabel.Bounds.Width, font)); authorLabel.GetText = () => author.Update(preview); } } @@ -203,13 +203,13 @@ namespace OpenRA.Mods.Common.Widgets.Logic } catch (System.Net.Sockets.SocketException e) { - var message = "Could not listen on port {0}.".F(Game.Settings.Server.ListenPort); + var message = $"Could not listen on port {Game.Settings.Server.ListenPort}."; // AddressAlreadyInUse (WSAEADDRINUSE) if (e.ErrorCode == 10048) message += "\nCheck if the port is already being used."; else - message += "\nError is: \"{0}\" ({1})".F(e.Message, e.ErrorCode); + message += $"\nError is: \"{e.Message}\" ({e.ErrorCode})"; ConfirmationDialogs.ButtonPrompt("Server Creation Failed", message, onCancel: () => { }, cancelText: "Back"); } diff --git a/OpenRA.Mods.Common/Widgets/Logic/ServerListLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/ServerListLogic.cs index 85b8b3a8a1..558d10b885 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/ServerListLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/ServerListLogic.cs @@ -313,10 +313,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic string PlayersLabel(GameServer game) { - return "{0}{1}{2}".F( - "{0} Player{1}".F(game.Players > 0 ? game.Players.ToString() : "No", game.Players != 1 ? "s" : ""), - game.Bots > 0 ? ", {0} Bot{1}".F(game.Bots, game.Bots != 1 ? "s" : "") : "", - game.Spectators > 0 ? ", {0} Spectator{1}".F(game.Spectators, game.Spectators != 1 ? "s" : "") : ""); + return $"{(game.Players > 0 ? game.Players.ToString() : "No")} Player{(game.Players != 1 ? "s" : "")}{(game.Bots > 0 ? $", {game.Bots} Bot{(game.Bots != 1 ? "s" : "")}" : "")}{(game.Spectators > 0 ? $", {game.Spectators} Spectator{(game.Spectators != 1 ? "s" : "")}" : "")}"; } public void RefreshServerList() @@ -466,7 +463,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var noTeams = players.Count() == 1; foreach (var p in players) { - var label = noTeams ? "Players" : p.Key == 0 ? "No Team" : "Team {0}".F(p.Key); + var label = noTeams ? "Players" : p.Key == 0 ? "No Team" : $"Team {p.Key}"; teams.Add(label, p); } @@ -634,8 +631,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic var players = item.GetOrNull("PLAYERS"); if (players != null) { - var label = "{0} / {1}".F(game.Players + game.Bots, game.MaxPlayers + game.Bots) - + (game.Spectators > 0 ? " + {0}".F(game.Spectators) : ""); + var label = $"{game.Players + game.Bots} / {game.MaxPlayers + game.Bots}" + + (game.Spectators > 0 ? $" + {game.Spectators}" : ""); var color = canJoin ? players.TextColor : incompatibleGameColor; players.GetText = () => label; @@ -647,7 +644,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (game.Clients.Length > 10) displayClients = displayClients .Take(9) - .Append("+ {0} other players".F(game.Clients.Length - 9)); + .Append($"+ {game.Clients.Length - 9} other players"); var tooltip = displayClients.JoinWith("\n"); players.GetTooltipText = () => tooltip; @@ -699,7 +696,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (game.PlayTime > 0) { var totalMinutes = Math.Ceiling(game.PlayTime / 60.0); - label += " for {0} minute{1}".F(totalMinutes, totalMinutes > 1 ? "s" : ""); + label += $" for {totalMinutes} minute{(totalMinutes > 1 ? "s" : "")}"; } return label; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Settings/DisplaySettingsLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Settings/DisplaySettingsLogic.cs index 82593c9bbd..03557ab1aa 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Settings/DisplaySettingsLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Settings/DisplaySettingsLogic.cs @@ -79,7 +79,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var displaySelectionDropDown = panel.Get("DISPLAY_SELECTION_DROPDOWN"); displaySelectionDropDown.OnMouseDown = _ => ShowDisplaySelectionDropdown(displaySelectionDropDown, ds); - var displaySelectionLabel = new CachedTransform(i => "Display {0}".F(i + 1)); + var displaySelectionLabel = new CachedTransform(i => $"Display {i + 1}"); displaySelectionDropDown.GetText = () => displaySelectionLabel.Update(ds.VideoDisplay); displaySelectionDropDown.IsDisabled = () => Game.Renderer.DisplayCount < 2; @@ -115,7 +115,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic }; var uiScaleDropdown = panel.Get("UI_SCALE_DROPDOWN"); - var uiScaleLabel = new CachedTransform(s => "{0}%".F((int)(100 * s))); + var uiScaleLabel = new CachedTransform(s => $"{(int)(100 * s)}%"); uiScaleDropdown.OnMouseDown = _ => ShowUIScaleDropdown(uiScaleDropdown, ds); uiScaleDropdown.GetText = () => uiScaleLabel.Update(ds.UIScale); @@ -142,7 +142,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic var frameLimitCheckbox = panel.Get("FRAME_LIMIT_CHECKBOX"); var frameLimitOrigLabel = frameLimitCheckbox.Text; - var frameLimitLabel = new CachedTransform(fps => frameLimitOrigLabel + " ({0} FPS)".F(fps)); + var frameLimitLabel = new CachedTransform(fps => frameLimitOrigLabel + $" ({fps} FPS)"); frameLimitCheckbox.GetText = () => frameLimitLabel.Update(ds.MaxFramerate); // Player profile @@ -285,7 +285,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic () => s.VideoDisplay == o, () => s.VideoDisplay = o); - var label = "Display {0}".F(o + 1); + var label = $"Display {o + 1}"; item.Get("LABEL").GetText = () => label; return item; }; @@ -421,7 +421,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic }); }); - var label = "{0}%".F((int)(100 * o)); + var label = $"{(int)(100 * o)}%"; item.Get("LABEL").GetText = () => label; return item; }; diff --git a/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsLogic.cs index 2e00cd0f87..cf1a4b551d 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsLogic.cs @@ -102,7 +102,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic }; ConfirmationDialogs.ButtonPrompt( - title: "Reset \"{0}\"".F(panels[activePanel]), + title: $"Reset \"{panels[activePanel]}\"", text: "Are you sure you want to reset\nall settings in this panel?", onConfirm: reset, onCancel: () => { }, diff --git a/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsUtils.cs b/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsUtils.cs index 51b57a6d0a..5031d33f42 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsUtils.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/Settings/SettingsUtils.cs @@ -20,7 +20,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var field = group.GetType().GetField(pref); if (field == null) - throw new InvalidOperationException("{0} does not contain a preference type {1}".F(group.GetType().Name, pref)); + throw new InvalidOperationException($"{group.GetType().Name} does not contain a preference type {pref}"); var cb = parent.Get(id); cb.IsChecked = () => (bool)field.GetValue(group); @@ -31,7 +31,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var field = group.GetType().GetField(pref); if (field == null) - throw new InvalidOperationException("{0} does not contain a preference type {1}".F(group.GetType().Name, pref)); + throw new InvalidOperationException($"{group.GetType().Name} does not contain a preference type {pref}"); var ss = parent.Get(id); ss.Value = (float)field.GetValue(group); @@ -42,7 +42,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { var field = group.GetType().GetField(pref); if (field == null) - throw new InvalidOperationException("{0} does not contain a preference type {1}".F(group.GetType().Name, pref)); + throw new InvalidOperationException($"{group.GetType().Name} does not contain a preference type {pref}"); var ss = parent.Get(id); ss.Value = (float)(int)field.GetValue(group); diff --git a/OpenRA.Mods.Common/Widgets/Logic/SystemInfoPromptLogic.cs b/OpenRA.Mods.Common/Widgets/Logic/SystemInfoPromptLogic.cs index d24da961a8..71a8750a2b 100644 --- a/OpenRA.Mods.Common/Widgets/Logic/SystemInfoPromptLogic.cs +++ b/OpenRA.Mods.Common/Widgets/Logic/SystemInfoPromptLogic.cs @@ -37,7 +37,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic { "x64process", ("Process is 64 bit", Environment.Is64BitProcess.ToString()) }, { "runtime", (".NET Runtime", Platform.RuntimeVersion) }, { "gl", ("OpenGL Version", Game.Renderer.GLVersion) }, - { "windowsize", ("Window Size", "{0}x{1}".F(Game.Renderer.NativeResolution.Width, Game.Renderer.NativeResolution.Height)) }, + { "windowsize", ("Window Size", $"{Game.Renderer.NativeResolution.Width}x{Game.Renderer.NativeResolution.Height}") }, { "windowscale", ("Window Scale", Game.Renderer.NativeWindowScale.ToString("F2", CultureInfo.InvariantCulture)) }, { "uiscale", ("UI Scale", Game.Settings.Graphics.UIScale.ToString("F2", CultureInfo.InvariantCulture)) }, { "lang", ("System Language", lang) } @@ -54,7 +54,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic if (!Game.Settings.Debug.SendSystemInformation) return ""; - return "&sysinfoversion={0}&".F(SystemInformationVersion) + return $"&sysinfoversion={SystemInformationVersion}&" + GetSystemInformation() .Select(kv => kv.Key + "=" + Uri.EscapeUriString(kv.Value.Value)) .JoinWith("&"); diff --git a/OpenRA.Mods.Common/Widgets/ProductionPaletteWidget.cs b/OpenRA.Mods.Common/Widgets/ProductionPaletteWidget.cs index 04c4870971..db30990ad8 100644 --- a/OpenRA.Mods.Common/Widgets/ProductionPaletteWidget.cs +++ b/OpenRA.Mods.Common/Widgets/ProductionPaletteWidget.cs @@ -139,7 +139,7 @@ namespace OpenRA.Mods.Common.Widgets return new string[0]; if (string.IsNullOrEmpty(prefix)) - emitError("{0} must define HotkeyPrefix if HotkeyCount > 0.".F(widgetNode.Location)); + emitError($"{widgetNode.Location} must define HotkeyPrefix if HotkeyCount > 0."); return Exts.MakeArray(count, i => prefix + (i + 1).ToString("D2")); } diff --git a/OpenRA.Mods.Common/Widgets/StrategicProgressWidget.cs b/OpenRA.Mods.Common/Widgets/StrategicProgressWidget.cs index ecf82f4c2f..29c97cd88c 100644 --- a/OpenRA.Mods.Common/Widgets/StrategicProgressWidget.cs +++ b/OpenRA.Mods.Common/Widgets/StrategicProgressWidget.cs @@ -65,9 +65,7 @@ namespace OpenRA.Mods.Common.Widgets var winnerSvc = pendingWinner.PlayerActor.Trait(); var isVictory = pendingWinner.RelationshipWith(world.LocalPlayer) == PlayerRelationship.Ally; - var tc = "Strategic {0} in {1}".F( - isVictory ? "victory" : "defeat", - WidgetUtils.FormatTime(winnerSvc.TicksLeft, world.Timestep)); + var tc = $"Strategic {(isVictory ? "victory" : "defeat")} in {WidgetUtils.FormatTime(winnerSvc.TicksLeft, world.Timestep)}"; var font = Game.Renderer.Fonts["Bold"]; diff --git a/OpenRA.Mods.Common/Widgets/SupportPowersWidget.cs b/OpenRA.Mods.Common/Widgets/SupportPowersWidget.cs index 619a262f25..156b7d0252 100644 --- a/OpenRA.Mods.Common/Widgets/SupportPowersWidget.cs +++ b/OpenRA.Mods.Common/Widgets/SupportPowersWidget.cs @@ -83,7 +83,7 @@ namespace OpenRA.Mods.Common.Widgets return new string[0]; if (string.IsNullOrEmpty(prefix)) - emitError("{0} must define HotkeyPrefix if HotkeyCount > 0.".F(widgetNode.Location)); + emitError($"{widgetNode.Location} must define HotkeyPrefix if HotkeyCount > 0."); return Exts.MakeArray(count, i => prefix + (i + 1).ToString("D2")); } diff --git a/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs b/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs index 09d67d66e3..f6a4804069 100644 --- a/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs +++ b/OpenRA.Mods.Common/Widgets/ViewportControllerWidget.cs @@ -123,10 +123,10 @@ namespace OpenRA.Mods.Common.Widgets yield break; if (string.IsNullOrEmpty(savePrefix)) - emitError("{0} must define BookmarkSaveKeyPrefix if BookmarkKeyCount > 0.".F(widgetNode.Location)); + emitError($"{widgetNode.Location} must define BookmarkSaveKeyPrefix if BookmarkKeyCount > 0."); if (string.IsNullOrEmpty(restorePrefix)) - emitError("{0} must define BookmarkRestoreKeyPrefix if BookmarkKeyCount > 0.".F(widgetNode.Location)); + emitError($"{widgetNode.Location} must define BookmarkRestoreKeyPrefix if BookmarkKeyCount > 0."); for (var i = 0; i < count; i++) { diff --git a/OpenRA.Mods.Common/Widgets/WidgetUtils.cs b/OpenRA.Mods.Common/Widgets/WidgetUtils.cs index 97500108ab..9fe207c85d 100644 --- a/OpenRA.Mods.Common/Widgets/WidgetUtils.cs +++ b/OpenRA.Mods.Common/Widgets/WidgetUtils.cs @@ -196,10 +196,10 @@ namespace OpenRA.Mods.Common.Widgets var minutes = seconds / 60; if (minutes >= 60) - return "{0:D}:{1:D2}:{2:D2}".F(minutes / 60, minutes % 60, seconds % 60); + return $"{minutes / 60:D}:{minutes % 60:D2}:{seconds % 60:D2}"; if (leadingMinuteZero) - return "{0:D2}:{1:D2}".F(minutes, seconds % 60); - return "{0:D}:{1:D2}".F(minutes, seconds % 60); + return $"{minutes:D2}:{seconds % 60:D2}"; + return $"{minutes:D}:{seconds % 60:D2}"; } public static string WrapText(string text, int width, SpriteFont font) diff --git a/OpenRA.Mods.D2k/Lint/CheckImportActors.cs b/OpenRA.Mods.D2k/Lint/CheckImportActors.cs index a0e8b5ea07..b25c900237 100644 --- a/OpenRA.Mods.D2k/Lint/CheckImportActors.cs +++ b/OpenRA.Mods.D2k/Lint/CheckImportActors.cs @@ -22,7 +22,7 @@ namespace OpenRA.Mods.D2k.Lint foreach (var actorData in D2kMapImporter.ActorDataByActorCode.Values) { if (!rules.Actors.ContainsKey(actorData.Actor)) - emitError("Undefined actor {0} in map import code.".F(actorData.Actor)); + emitError($"Undefined actor {actorData.Actor} in map import code."); } } } diff --git a/OpenRA.Mods.D2k/SpriteLoaders/R8Loader.cs b/OpenRA.Mods.D2k/SpriteLoaders/R8Loader.cs index 1cfbec3f0c..1053c08dda 100644 --- a/OpenRA.Mods.D2k/SpriteLoaders/R8Loader.cs +++ b/OpenRA.Mods.D2k/SpriteLoaders/R8Loader.cs @@ -51,7 +51,7 @@ namespace OpenRA.Mods.D2k.SpriteLoaders var paletteOffset = s.ReadInt32(); var bpp = s.ReadUInt8(); if (bpp != 8) - throw new InvalidDataException("Error: {0} bits per pixel are not supported.".F(bpp)); + throw new InvalidDataException($"Error: {bpp} bits per pixel are not supported."); var frameHeight = s.ReadUInt8(); var frameWidth = s.ReadUInt8(); diff --git a/OpenRA.Mods.D2k/Traits/World/D2kResourceRenderer.cs b/OpenRA.Mods.D2k/Traits/World/D2kResourceRenderer.cs index 464ba13d9d..19c8cfe710 100644 --- a/OpenRA.Mods.D2k/Traits/World/D2kResourceRenderer.cs +++ b/OpenRA.Mods.D2k/Traits/World/D2kResourceRenderer.cs @@ -161,7 +161,7 @@ namespace OpenRA.Mods.D2k.Traits UpdateSpriteLayers(cell, content.Sequence, index, content.Palette); } else - throw new InvalidOperationException("SpriteMap does not contain an index for ClearSides type '{0}'".F(clear)); + throw new InvalidOperationException($"SpriteMap does not contain an index for ClearSides type '{clear}'"); } else UpdateSpriteLayers(cell, null, 0, null); diff --git a/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs b/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs index c6f1b5fdb3..b84ceba17f 100644 --- a/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs +++ b/OpenRA.Mods.D2k/UtilityCommands/D2kMapImporter.cs @@ -357,7 +357,7 @@ namespace OpenRA.Mods.D2k.UtilityCommands { var kvp = ActorDataByActorCode[tileSpecialInfo]; if (!rules.Actors.ContainsKey(kvp.Actor.ToLowerInvariant())) - throw new InvalidOperationException("Actor with name {0} could not be found in the rules YAML file!".F(kvp.Actor)); + throw new InvalidOperationException($"Actor with name {kvp.Actor} could not be found in the rules YAML file!"); var a = new ActorReference(kvp.Actor) { @@ -487,8 +487,8 @@ namespace OpenRA.Mods.D2k.UtilityCommands if (template == null) { var pos = GetCurrentTilePositionOnMap(); - Console.WriteLine("Tile with index {0} could not be found in the tileset YAML file!".F(tileIndex)); - Console.WriteLine("Defaulting to a \"clear\" tile for coordinates ({0}, {1})!".F(pos.X, pos.Y)); + Console.WriteLine($"Tile with index {tileIndex} could not be found in the tileset YAML file!"); + Console.WriteLine($"Defaulting to a \"clear\" tile for coordinates ({pos.X}, {pos.Y})!"); return clearTile; } diff --git a/OpenRA.Platforms.Default/FrameBuffer.cs b/OpenRA.Platforms.Default/FrameBuffer.cs index 7a75ac6a56..445aba1774 100644 --- a/OpenRA.Platforms.Default/FrameBuffer.cs +++ b/OpenRA.Platforms.Default/FrameBuffer.cs @@ -30,7 +30,7 @@ namespace OpenRA.Platforms.Default this.size = size; this.clearColor = clearColor; if (!Exts.IsPowerOf2(size.Width) || !Exts.IsPowerOf2(size.Height)) - throw new InvalidDataException("Frame buffer size ({0}x{1}) must be a power of two".F(size.Width, size.Height)); + throw new InvalidDataException($"Frame buffer size ({size.Width}x{size.Height}) must be a power of two"); OpenGL.glGenFramebuffers(1, out framebuffer); OpenGL.CheckGLError(); @@ -61,7 +61,7 @@ namespace OpenRA.Platforms.Default var status = OpenGL.glCheckFramebufferStatus(OpenGL.GL_FRAMEBUFFER); if (status != OpenGL.GL_FRAMEBUFFER_COMPLETE) { - var error = "Error creating framebuffer: {0}\n{1}".F(status, new StackTrace()); + var error = $"Error creating framebuffer: {status}\n{new StackTrace()}"; OpenGL.WriteGraphicsLog(error); throw new InvalidOperationException("OpenGL Error: See graphics.log for details."); } diff --git a/OpenRA.Platforms.Default/OpenGL.cs b/OpenRA.Platforms.Default/OpenGL.cs index 15ef0647d9..fc7adbee53 100644 --- a/OpenRA.Platforms.Default/OpenGL.cs +++ b/OpenRA.Platforms.Default/OpenGL.cs @@ -646,7 +646,7 @@ namespace OpenRA.Platforms.Default } catch (Exception e) { - WriteGraphicsLog("Failed to initialize OpenGL bindings.\nInner exception was: {0}".F(e)); + WriteGraphicsLog($"Failed to initialize OpenGL bindings.\nInner exception was: {e}"); throw new InvalidProgramException("Failed to initialize OpenGL. See graphics.log for details.", e); } } @@ -750,7 +750,7 @@ namespace OpenRA.Platforms.Default string errorText; errorText = ErrorToText.TryGetValue(type, out errorText) ? errorText : type.ToString("X"); - var error = "GL Error: {0}\n{1}".F(errorText, new StackTrace()); + var error = $"GL Error: {errorText}\n{new StackTrace()}"; WriteGraphicsLog(error); @@ -791,7 +791,7 @@ namespace OpenRA.Platforms.Default severityText = DebugSeverityToText.TryGetValue(severity, out severityText) ? severityText : severity.ToString("X"); var messageText = message.ToString(); - return "{0} - GL Debug {1} Output: {2} - {3}\n{4}".F(severityText, sourceText, typeText, messageText, new StackTrace()); + return $"{severityText} - GL Debug {sourceText} Output: {typeText} - {messageText}\n{new StackTrace()}"; } } } diff --git a/OpenRA.Platforms.Default/Sdl2GraphicsContext.cs b/OpenRA.Platforms.Default/Sdl2GraphicsContext.cs index 0faac1cc85..6e4ccf065d 100644 --- a/OpenRA.Platforms.Default/Sdl2GraphicsContext.cs +++ b/OpenRA.Platforms.Default/Sdl2GraphicsContext.cs @@ -33,7 +33,7 @@ namespace OpenRA.Platforms.Default context = SDL.SDL_GL_CreateContext(window.Window); if (context == IntPtr.Zero || SDL.SDL_GL_MakeCurrent(window.Window, context) < 0) - throw new InvalidOperationException("Can not create OpenGL context. (Error: {0})".F(SDL.SDL_GetError())); + throw new InvalidOperationException($"Can not create OpenGL context. (Error: {SDL.SDL_GetError()})"); OpenGL.Initialize(window.GLProfile == GLProfile.Legacy); OpenGL.CheckGLError(); diff --git a/OpenRA.Platforms.Default/Sdl2HardwareCursor.cs b/OpenRA.Platforms.Default/Sdl2HardwareCursor.cs index 442311325c..57b5ca535e 100644 --- a/OpenRA.Platforms.Default/Sdl2HardwareCursor.cs +++ b/OpenRA.Platforms.Default/Sdl2HardwareCursor.cs @@ -37,7 +37,7 @@ namespace OpenRA.Platforms.Default { surface = SDL.SDL_CreateRGBSurface(0, size.Width, size.Height, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); if (surface == IntPtr.Zero) - throw new InvalidDataException("Failed to create surface: {0}".F(SDL.SDL_GetError())); + throw new InvalidDataException($"Failed to create surface: {SDL.SDL_GetError()}"); var sur = (SDL.SDL_Surface)Marshal.PtrToStructure(surface, typeof(SDL.SDL_Surface)); Marshal.Copy(data, 0, sur.pixels, data.Length); @@ -47,7 +47,7 @@ namespace OpenRA.Platforms.Default Cursor = SDL.SDL_CreateColorCursor(surface, hotspot.X, hotspot.Y); if (Cursor == IntPtr.Zero) - throw new Sdl2HardwareCursorException("Failed to create cursor: {0}".F(SDL.SDL_GetError())); + throw new Sdl2HardwareCursorException($"Failed to create cursor: {SDL.SDL_GetError()}"); } catch { diff --git a/OpenRA.Platforms.Default/Sdl2PlatformWindow.cs b/OpenRA.Platforms.Default/Sdl2PlatformWindow.cs index 15bc5eab4a..28a4389350 100644 --- a/OpenRA.Platforms.Default/Sdl2PlatformWindow.cs +++ b/OpenRA.Platforms.Default/Sdl2PlatformWindow.cs @@ -349,7 +349,7 @@ namespace OpenRA.Platforms.Default } catch (Exception ex) { - throw new Sdl2HardwareCursorException("Failed to create hardware cursor `{0}` - {1}".F(name, ex.Message), ex); + throw new Sdl2HardwareCursorException($"Failed to create hardware cursor `{name}` - {ex.Message}", ex); } } diff --git a/OpenRA.Platforms.Default/Shader.cs b/OpenRA.Platforms.Default/Shader.cs index 0326db1829..cfe7590e71 100644 --- a/OpenRA.Platforms.Default/Shader.cs +++ b/OpenRA.Platforms.Default/Shader.cs @@ -60,7 +60,7 @@ namespace OpenRA.Platforms.Default OpenGL.glGetShaderInfoLog(shader, len, out _, log); Log.Write("graphics", "GL Info Log:\n{0}", log.ToString()); - throw new InvalidProgramException("Compile error in shader object '{0}'".F(filename)); + throw new InvalidProgramException($"Compile error in shader object '{filename}'"); } return shader; @@ -106,7 +106,7 @@ namespace OpenRA.Platforms.Default var log = new StringBuilder(len); OpenGL.glGetProgramInfoLog(program, len, out _, log); Log.Write("graphics", "GL Info Log:\n{0}", log.ToString()); - throw new InvalidProgramException("Link error in shader program '{0}'".F(name)); + throw new InvalidProgramException($"Link error in shader program '{name}'"); } OpenGL.glUseProgram(program); diff --git a/OpenRA.Platforms.Default/Texture.cs b/OpenRA.Platforms.Default/Texture.cs index 75186bd19f..a3feb44e2c 100644 --- a/OpenRA.Platforms.Default/Texture.cs +++ b/OpenRA.Platforms.Default/Texture.cs @@ -82,7 +82,7 @@ namespace OpenRA.Platforms.Default { VerifyThreadAffinity(); if (!Exts.IsPowerOf2(width) || !Exts.IsPowerOf2(height)) - throw new InvalidDataException("Non-power-of-two array {0}x{1}".F(width, height)); + throw new InvalidDataException($"Non-power-of-two array {width}x{height}"); Size = new Size(width, height); unsafe @@ -100,7 +100,7 @@ namespace OpenRA.Platforms.Default var height = colors.GetUpperBound(0) + 1; if (!Exts.IsPowerOf2(width) || !Exts.IsPowerOf2(height)) - throw new InvalidDataException("Non-power-of-two array {0}x{1}".F(width, height)); + throw new InvalidDataException($"Non-power-of-two array {width}x{height}"); Size = new Size(width, height); unsafe @@ -180,7 +180,7 @@ namespace OpenRA.Platforms.Default { VerifyThreadAffinity(); if (!Exts.IsPowerOf2(width) || !Exts.IsPowerOf2(height)) - throw new InvalidDataException("Non-power-of-two array {0}x{1}".F(width, height)); + throw new InvalidDataException($"Non-power-of-two array {width}x{height}"); Size = new Size(width, height); SetData(IntPtr.Zero, width, height); diff --git a/OpenRA.Utility/Program.cs b/OpenRA.Utility/Program.cs index 1b20596f7a..20b1fd9836 100644 --- a/OpenRA.Utility/Program.cs +++ b/OpenRA.Utility/Program.cs @@ -24,7 +24,7 @@ namespace OpenRA { public readonly string Command; public NoSuchCommandException(string command) - : base("No such command '{0}'".F(command)) + : base($"No such command '{command}'") { Command = command; }