diff --git a/.editorconfig b/.editorconfig
index f275e86cac..b7b73db086 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -138,7 +138,7 @@ dotnet_diagnostic.IDE0017.severity = warning
# IDE0028 Use collection initializers
#dotnet_style_collection_initializer = true
-dotnet_diagnostic.IDE0028.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0028.severity = warning
# IDE0029/IDE0030/IDE0270 Use coalesce expression (non-nullable types)/Use coalesce expression (nullable types)/Use coalesce expression (if null)
#dotnet_style_coalesce_expression = true
@@ -308,27 +308,27 @@ dotnet_diagnostic.IDE0241.severity = warning
# IDE0300 Use collection expression for array
# From above, uses dotnet_style_prefer_collection_expression
-dotnet_diagnostic.IDE0300.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0300.severity = warning
# IDE0301 Use collection expression for empty
# From above, uses dotnet_style_prefer_collection_expression
-dotnet_diagnostic.IDE0301.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0301.severity = warning
# IDE0302 Use collection expression for stackalloc
# From above, uses dotnet_style_prefer_collection_expression
-dotnet_diagnostic.IDE0302.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0302.severity = warning
# IDE0303 Use collection expression for 'Create()'
# From above, uses dotnet_style_prefer_collection_expression
-dotnet_diagnostic.IDE0303.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0303.severity = warning
# IDE0304 Use collection expression for builder
# From above, uses dotnet_style_prefer_collection_expression
-dotnet_diagnostic.IDE0304.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0304.severity = warning
# IDE0305 Use collection expression for fluent
# From above, uses dotnet_style_prefer_collection_expression
-dotnet_diagnostic.IDE0305.severity = suggestion # TODO: Consider enabling
+dotnet_diagnostic.IDE0305.severity = silent
## Field preferences
diff --git a/OpenRA.Game/Actor.cs b/OpenRA.Game/Actor.cs
index 1e6b245ace..c2b35f7d75 100644
--- a/OpenRA.Game/Actor.cs
+++ b/OpenRA.Game/Actor.cs
@@ -89,21 +89,21 @@ namespace OpenRA
sealed class ConditionState
{
/// Delegates that have registered to be notified when this condition changes.
- public readonly List Notifiers = new();
+ public readonly List Notifiers = [];
/// Unique integers identifying granted instances of the condition.
- public readonly HashSet Tokens = new();
+ public readonly HashSet Tokens = [];
}
- readonly Dictionary conditionStates = new();
+ readonly Dictionary conditionStates = [];
/// Each granted condition receives a unique token that is used when revoking.
- readonly Dictionary conditionTokens = new();
+ readonly Dictionary conditionTokens = [];
int nextConditionToken = 1;
/// Cache of condition -> enabled state for quick evaluation of token counter conditions.
- readonly Dictionary conditionCache = new();
+ readonly Dictionary conditionCache = [];
/// Read-only version of conditionCache that is passed to IConditionConsumers.
readonly IReadOnlyDictionary readOnlyConditionCache;
@@ -541,7 +541,7 @@ namespace OpenRA
if (EnabledTargetablePositions.Any())
return enabledTargetableWorldPositions;
- return new[] { CenterPosition };
+ return [CenterPosition];
}
#region Conditions
diff --git a/OpenRA.Game/CVec.cs b/OpenRA.Game/CVec.cs
index c4706ce394..f0a90864cc 100644
--- a/OpenRA.Game/CVec.cs
+++ b/OpenRA.Game/CVec.cs
@@ -62,7 +62,7 @@ namespace OpenRA
public override string ToString() { return X + "," + Y; }
public static readonly CVec[] Directions =
- {
+ [
new(-1, -1),
new(-1, 0),
new(-1, 1),
@@ -71,7 +71,7 @@ namespace OpenRA
new(1, -1),
new(1, 0),
new(1, 1),
- };
+ ];
#region Scripting interface
diff --git a/OpenRA.Game/CryptoUtil.cs b/OpenRA.Game/CryptoUtil.cs
index 89285ff0fb..f568160a73 100644
--- a/OpenRA.Game/CryptoUtil.cs
+++ b/OpenRA.Game/CryptoUtil.cs
@@ -20,7 +20,7 @@ namespace OpenRA
public static class CryptoUtil
{
// Fixed byte pattern for the OID header
- static readonly byte[] OIDHeader = { 0x30, 0xD, 0x6, 0x9, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0 };
+ static readonly byte[] OIDHeader = [0x30, 0xD, 0x6, 0x9, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0];
static readonly char[] HexUpperAlphabet = "0123456789ABCDEF".ToArray();
static readonly char[] HexLowerAlphabet = "0123456789abcdef".ToArray();
diff --git a/OpenRA.Game/ExternalMods.cs b/OpenRA.Game/ExternalMods.cs
index 2cb1c42cf9..40dff9d933 100644
--- a/OpenRA.Game/ExternalMods.cs
+++ b/OpenRA.Game/ExternalMods.cs
@@ -40,7 +40,7 @@ namespace OpenRA
public class ExternalMods : IReadOnlyDictionary
{
- readonly Dictionary mods = new();
+ readonly Dictionary mods = [];
readonly SheetBuilder sheetBuilder;
Sheet CreateSheet()
@@ -122,13 +122,13 @@ namespace OpenRA
return;
var key = ExternalMod.MakeKey(mod);
- var yaml = new MiniYamlNode("Registration", new MiniYaml("", new[]
- {
+ var yaml = new MiniYamlNode("Registration", new MiniYaml("",
+ [
new MiniYamlNode("Id", mod.Id),
new MiniYamlNode("Version", mod.Metadata.Version),
new MiniYamlNode("LaunchPath", launchPath),
new MiniYamlNode("LaunchArgs", new[] { "Game.Mod=" + mod.Id }.Concat(launchArgs).JoinWith(", "))
- }));
+ ]));
var iconNodes = new List();
diff --git a/OpenRA.Game/Exts.cs b/OpenRA.Game/Exts.cs
index a01a62d205..1511835fa4 100644
--- a/OpenRA.Game/Exts.cs
+++ b/OpenRA.Game/Exts.cs
@@ -413,11 +413,6 @@ namespace OpenRA
return ts.Except(exclusions);
}
- public static HashSet ToHashSet(this IEnumerable source)
- {
- return new HashSet(source);
- }
-
public static Dictionary ToDictionaryWithConflictLog(
this IEnumerable source, Func keySelector,
string debugName, Func logKey, Func logValue)
@@ -460,14 +455,14 @@ namespace OpenRA
// Check for a key conflict:
if (!output.TryAdd(key, element))
{
- dupKeys ??= new Dictionary>();
+ dupKeys ??= [];
if (!dupKeys.TryGetValue(key, out var dupKeyMessages))
{
// Log the initial conflicting value already inserted:
- dupKeyMessages = new List
- {
+ dupKeyMessages =
+ [
logValue(output[key])
- };
+ ];
dupKeys.Add(key, dupKeyMessages);
}
@@ -664,7 +659,7 @@ namespace OpenRA
if (index == -1)
{
// The remaining string is an empty string
- str = ReadOnlySpan.Empty;
+ str = [];
Current = span;
return true;
}
diff --git a/OpenRA.Game/FieldLoader.cs b/OpenRA.Game/FieldLoader.cs
index a8a62a5ce2..c81a71a9a8 100644
--- a/OpenRA.Game/FieldLoader.cs
+++ b/OpenRA.Game/FieldLoader.cs
@@ -530,8 +530,8 @@ namespace OpenRA
if (value != null)
{
var parts = value.Split(SplitComma, StringSplitOptions.RemoveEmptyEntries);
- var ctor = fieldType.GetConstructor(new[] { typeof(string[]) });
- return ctor.Invoke(new object[] { parts.Select(p => p.Trim()).ToArray() });
+ var ctor = fieldType.GetConstructor([typeof(string[])]);
+ return ctor.Invoke([parts.Select(p => p.Trim()).ToArray()]);
}
return InvalidValueAction(value, fieldType, fieldName);
@@ -544,7 +544,7 @@ namespace OpenRA
var innerType = fieldType.GetGenericArguments()[0];
var innerValue = GetValue("Nullable", innerType, value, field);
- return fieldType.GetConstructor(new[] { innerType }).Invoke(new[] { innerValue });
+ return fieldType.GetConstructor([innerType]).Invoke([innerValue]);
}
public static void Load(object self, MiniYaml my)
@@ -565,7 +565,7 @@ namespace OpenRA
val = fli.Loader(my);
else
{
- missing ??= new List();
+ missing ??= [];
missing.Add(fli.YamlName);
continue;
}
@@ -576,7 +576,7 @@ namespace OpenRA
{
if (fli.Attribute.Required)
{
- missing ??= new List();
+ missing ??= [];
missing.Add(fli.YamlName);
}
diff --git a/OpenRA.Game/FileFormats/Png.cs b/OpenRA.Game/FileFormats/Png.cs
index f4b603fba0..e033e2940d 100644
--- a/OpenRA.Game/FileFormats/Png.cs
+++ b/OpenRA.Game/FileFormats/Png.cs
@@ -25,14 +25,14 @@ namespace OpenRA.FileFormats
{
public class Png
{
- static readonly byte[] Signature = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };
+ static readonly byte[] Signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
public int Width { get; }
public int Height { get; }
public Color[] Palette { get; }
public byte[] Data { get; }
public SpriteFrameType Type { get; }
- public Dictionary EmbeddedData = new();
+ public Dictionary EmbeddedData = [];
public int PixelStride => Type == SpriteFrameType.Indexed8 ? 1 : Type == SpriteFrameType.Rgb24 ? 3 : 4;
diff --git a/OpenRA.Game/FileSystem/FileSystem.cs b/OpenRA.Game/FileSystem/FileSystem.cs
index 5178efc164..bbc710a549 100644
--- a/OpenRA.Game/FileSystem/FileSystem.cs
+++ b/OpenRA.Game/FileSystem/FileSystem.cs
@@ -29,16 +29,16 @@ namespace OpenRA.FileSystem
public class FileSystem : IReadOnlyFileSystem
{
public IEnumerable MountedPackages => mountedPackages.Keys;
- readonly Dictionary mountedPackages = new();
- readonly Dictionary explicitMounts = new();
+ readonly Dictionary mountedPackages = [];
+ readonly Dictionary explicitMounts = [];
readonly string modID;
// Mod packages that should not be disposed
- readonly List modPackages = new();
+ readonly List modPackages = [];
readonly IReadOnlyDictionary installedMods;
readonly IPackageLoader[] packageLoaders;
- Cache> fileIndex = new(_ => new List());
+ Cache> fileIndex = new(_ => []);
public FileSystem(string modID, IReadOnlyDictionary installedMods, IPackageLoader[] packageLoaders)
{
@@ -178,7 +178,7 @@ namespace OpenRA.FileSystem
explicitMounts.Clear();
modPackages.Clear();
- fileIndex = new Cache>(_ => new List());
+ fileIndex = new Cache>(_ => []);
}
public void TrimExcess()
diff --git a/OpenRA.Game/FluentBundle.cs b/OpenRA.Game/FluentBundle.cs
index fc7cde5262..b7511d44f1 100644
--- a/OpenRA.Game/FluentBundle.cs
+++ b/OpenRA.Game/FluentBundle.cs
@@ -128,7 +128,7 @@ namespace OpenRA
throw new ArgumentException("Expected a comma separated list of name, value arguments " +
"but the number of arguments is not a multiple of two", nameof(args));
- fluentArgs = new Dictionary();
+ fluentArgs = [];
for (var i = 0; i < args.Length; i += 2)
{
var argKey = args[i] as string;
diff --git a/OpenRA.Game/Game.cs b/OpenRA.Game/Game.cs
index fca786f774..e6d94e6cd3 100644
--- a/OpenRA.Game/Game.cs
+++ b/OpenRA.Game/Game.cs
@@ -356,7 +356,7 @@ namespace OpenRA
var explicitModPaths = Array.Empty();
if (modID != null && (File.Exists(modID) || Directory.Exists(modID)))
{
- explicitModPaths = new[] { modID };
+ explicitModPaths = [modID];
modID = Path.GetFileNameWithoutExtension(modID);
}
@@ -402,7 +402,7 @@ namespace OpenRA
var modSearchArg = args.GetValue("Engine.ModSearchPaths", null);
var modSearchPaths = modSearchArg != null ?
FieldLoader.GetValue("Engine.ModsPath", modSearchArg) :
- new[] { Path.Combine(Platform.EngineDir, "mods") };
+ [Path.Combine(Platform.EngineDir, "mods")];
Mods = new InstalledMods(modSearchPaths, explicitModPaths);
Console.WriteLine("Internal mods:");
diff --git a/OpenRA.Game/GameInformation.cs b/OpenRA.Game/GameInformation.cs
index 9149b35d65..7017fa3d7c 100644
--- a/OpenRA.Game/GameInformation.cs
+++ b/OpenRA.Game/GameInformation.cs
@@ -39,7 +39,7 @@ namespace OpenRA
public TimeSpan Duration => EndTimeUtc > StartTimeUtc ? EndTimeUtc - StartTimeUtc : TimeSpan.Zero;
public IList Players { get; }
- public HashSet DisabledSpawnPoints = new();
+ public HashSet DisabledSpawnPoints = [];
public MapPreview MapPreview => Game.ModData.MapCache[MapUid];
public IEnumerable HumanPlayers { get { return Players.Where(p => p.IsHuman); } }
public bool IsSinglePlayer => HumanPlayers.Count() == 1;
@@ -48,8 +48,8 @@ namespace OpenRA
public GameInformation()
{
- Players = new List();
- playersByRuntime = new Dictionary();
+ Players = [];
+ playersByRuntime = [];
}
public static GameInformation Deserialize(string data, string path)
diff --git a/OpenRA.Game/GameRules/ActorInfo.cs b/OpenRA.Game/GameRules/ActorInfo.cs
index d4bcbc3c99..8518daf14f 100644
--- a/OpenRA.Game/GameRules/ActorInfo.cs
+++ b/OpenRA.Game/GameRules/ActorInfo.cs
@@ -32,7 +32,7 @@ namespace OpenRA
/// You can remove inherited traits by adding a - in front of them as in -TraitName: to inherit everything, but this trait.
///
public readonly string Name;
- readonly TypeDictionary traits = new();
+ readonly TypeDictionary traits = [];
TraitInfo[] constructOrderCache = null;
public ActorInfo(ObjectCreator creator, string name, MiniYaml node)
diff --git a/OpenRA.Game/GameRules/SoundInfo.cs b/OpenRA.Game/GameRules/SoundInfo.cs
index e2711ccf45..8f704d54b6 100644
--- a/OpenRA.Game/GameRules/SoundInfo.cs
+++ b/OpenRA.Game/GameRules/SoundInfo.cs
@@ -17,14 +17,14 @@ namespace OpenRA.GameRules
{
public class SoundInfo
{
- public readonly Dictionary Variants = new();
- public readonly Dictionary Prefixes = new();
- public readonly Dictionary Voices = new();
- public readonly Dictionary Notifications = new();
+ public readonly Dictionary Variants = [];
+ public readonly Dictionary Prefixes = [];
+ public readonly Dictionary Voices = [];
+ public readonly Dictionary Notifications = [];
public readonly string DefaultVariant = ".aud";
public readonly string DefaultPrefix = "";
- public readonly HashSet DisableVariants = new();
- public readonly HashSet DisablePrefixes = new();
+ public readonly HashSet DisableVariants = [];
+ public readonly HashSet DisablePrefixes = [];
public readonly Lazy> VoicePools;
public readonly Lazy> NotificationsPools;
@@ -69,7 +69,7 @@ namespace OpenRA.GameRules
public readonly float VolumeModifier;
public readonly InterruptType Type;
readonly string[] clips;
- readonly List liveclips = new();
+ readonly List liveclips = [];
public SoundPool(float volumeModifier, InterruptType interruptType, params string[] clips)
{
diff --git a/OpenRA.Game/GameRules/WeaponInfo.cs b/OpenRA.Game/GameRules/WeaponInfo.cs
index bac06ff470..adb8c26e69 100644
--- a/OpenRA.Game/GameRules/WeaponInfo.cs
+++ b/OpenRA.Game/GameRules/WeaponInfo.cs
@@ -36,7 +36,7 @@ namespace OpenRA.GameRules
public class WarheadArgs
{
public WeaponInfo Weapon;
- public int[] DamageModifiers = Array.Empty();
+ public int[] DamageModifiers = [];
public WPos? Source;
public WRot ImpactOrientation;
public WPos ImpactPosition;
@@ -116,7 +116,7 @@ namespace OpenRA.GameRules
[Desc("Delay in ticks between firing shots from the same ammo magazine. If one entry, it will be used for all bursts.",
"If multiple entries, their number needs to match Burst - 1.")]
- public readonly int[] BurstDelays = { 5 };
+ public readonly int[] BurstDelays = [5];
[Desc("The minimum range the weapon can fire.")]
public readonly WDist MinRange = WDist.Zero;
@@ -128,7 +128,7 @@ namespace OpenRA.GameRules
public readonly IProjectileInfo Projectile;
[FieldLoader.LoadUsing(nameof(LoadWarheads))]
- public readonly List Warheads = new();
+ public readonly List Warheads = [];
///
/// This constructor is used solely for documentation generation.
@@ -139,7 +139,7 @@ namespace OpenRA.GameRules
{
// Resolve any weapon-level yaml inheritance or removals
// HACK: The "Defaults" sequence syntax prevents us from doing this generally during yaml parsing
- content = content.WithNodes(MiniYaml.Merge(new IReadOnlyCollection[] { content.Nodes }));
+ content = content.WithNodes(MiniYaml.Merge([content.Nodes]));
FieldLoader.Load(this, content);
}
diff --git a/OpenRA.Game/Graphics/Animation.cs b/OpenRA.Game/Graphics/Animation.cs
index d2ce02874b..9397f2058f 100644
--- a/OpenRA.Game/Graphics/Animation.cs
+++ b/OpenRA.Game/Graphics/Animation.cs
@@ -73,10 +73,10 @@ namespace OpenRA.Graphics
shadow, pos, offset - new WVec(0, 0, height), CurrentSequence.ShadowZOffset + zOffset + height, palette,
CurrentSequence.Scale, 1f, float3.Ones, tintModifiers,
true, rotation);
- return new IRenderable[] { shadowRenderable, imageRenderable };
+ return [shadowRenderable, imageRenderable];
}
- return new IRenderable[] { imageRenderable };
+ return [imageRenderable];
}
public IRenderable[] RenderUI(WorldRenderer wr, int2 pos, in WVec offset, int zOffset, PaletteReference palette, float scale = 1f, float rotation = 0f)
@@ -92,10 +92,10 @@ namespace OpenRA.Graphics
{
var shadowPos = pos - new int2((int)(scale * shadow.Size.X / 2), (int)(scale * shadow.Size.Y / 2));
var shadowRenderable = new UISpriteRenderable(shadow, WPos.Zero + offset, shadowPos, CurrentSequence.ShadowZOffset + zOffset, palette, scale, 1f, rotation);
- return new IRenderable[] { shadowRenderable, imageRenderable };
+ return [shadowRenderable, imageRenderable];
}
- return new IRenderable[] { imageRenderable };
+ return [imageRenderable];
}
public Rectangle ScreenBounds(WorldRenderer wr, WPos pos, in WVec offset)
diff --git a/OpenRA.Game/Graphics/ChromeProvider.cs b/OpenRA.Game/Graphics/ChromeProvider.cs
index 49e6f95c93..ba20c69d40 100644
--- a/OpenRA.Game/Graphics/ChromeProvider.cs
+++ b/OpenRA.Game/Graphics/ChromeProvider.cs
@@ -49,7 +49,7 @@ namespace OpenRA.Graphics
public readonly int[] PanelRegion = null;
public readonly PanelSides PanelSides = PanelSides.All;
- public readonly Dictionary Regions = new();
+ public readonly Dictionary Regions = [];
}
public static IReadOnlyDictionary Collections => collections;
@@ -71,11 +71,11 @@ namespace OpenRA.Graphics
dpiScale = Game.Renderer.WindowScale;
fileSystem = modData.DefaultFileSystem;
- collections = new Dictionary();
- cachedSheets = new Dictionary();
- cachedSprites = new Dictionary>();
- cachedPanelSprites = new Dictionary();
- cachedCollectionSheets = new Dictionary();
+ collections = [];
+ cachedSheets = [];
+ cachedSprites = [];
+ cachedPanelSprites = [];
+ cachedCollectionSheets = [];
var stringPool = new HashSet(); // Reuse common strings in YAML
var chrome = MiniYaml.Merge(modData.Manifest.Chrome
@@ -170,7 +170,7 @@ namespace OpenRA.Graphics
var sheetDensity = SheetForCollection(collection);
if (cachedCollection == null)
{
- cachedCollection = new Dictionary();
+ cachedCollection = [];
cachedSprites.Add(collectionName, cachedCollection);
}
@@ -240,11 +240,11 @@ namespace OpenRA.Graphics
// PERF: We don't need to search for images if there are no definitions.
// PERF: It's more efficient to send an empty array rather than an array of 9 nulls.
if (collection.Regions.Count == 0)
- return Array.Empty();
+ return [];
// Support manual definitions for unusual dialog layouts
- sprites = new[]
- {
+ sprites =
+ [
TryGetImage(collectionName, "corner-tl"),
TryGetImage(collectionName, "border-t"),
TryGetImage(collectionName, "corner-tr"),
@@ -254,7 +254,7 @@ namespace OpenRA.Graphics
TryGetImage(collectionName, "corner-bl"),
TryGetImage(collectionName, "border-b"),
TryGetImage(collectionName, "corner-br")
- };
+ ];
}
cachedPanelSprites.Add(collectionName, sprites);
diff --git a/OpenRA.Game/Graphics/CursorManager.cs b/OpenRA.Game/Graphics/CursorManager.cs
index 8c7e480183..1837c1a048 100644
--- a/OpenRA.Game/Graphics/CursorManager.cs
+++ b/OpenRA.Game/Graphics/CursorManager.cs
@@ -29,7 +29,7 @@ namespace OpenRA.Graphics
public IHardwareCursor[] Cursors;
}
- readonly Dictionary cursors = new();
+ readonly Dictionary cursors = [];
readonly SheetBuilder sheetBuilder;
readonly GraphicSettings graphicSettings;
@@ -233,7 +233,7 @@ namespace OpenRA.Graphics
var height = frame.Size.Height;
if (width == 0 || height == 0)
- return Array.Empty();
+ return [];
var data = new byte[4 * width * height];
unsafe
diff --git a/OpenRA.Game/Graphics/HardwarePalette.cs b/OpenRA.Game/Graphics/HardwarePalette.cs
index 4c111eb2bc..315dd09a67 100644
--- a/OpenRA.Game/Graphics/HardwarePalette.cs
+++ b/OpenRA.Game/Graphics/HardwarePalette.cs
@@ -21,11 +21,11 @@ namespace OpenRA.Graphics
public ITexture ColorShifts { get; }
public int Height { get; private set; }
- readonly Dictionary palettes = new();
- readonly Dictionary mutablePalettes = new();
- readonly Dictionary indices = new();
- byte[] buffer = Array.Empty();
- float[] colorShiftBuffer = Array.Empty();
+ readonly Dictionary palettes = [];
+ readonly Dictionary mutablePalettes = [];
+ readonly Dictionary indices = [];
+ byte[] buffer = [];
+ float[] colorShiftBuffer = [];
public HardwarePalette()
{
diff --git a/OpenRA.Game/Graphics/ModelVertex.cs b/OpenRA.Game/Graphics/ModelVertex.cs
index 0eecad7a9a..3d9f861b0c 100644
--- a/OpenRA.Game/Graphics/ModelVertex.cs
+++ b/OpenRA.Game/Graphics/ModelVertex.cs
@@ -43,11 +43,11 @@ namespace OpenRA.Graphics
: base("model")
{ }
- public override ShaderVertexAttribute[] Attributes { get; } = new[]
- {
+ public override ShaderVertexAttribute[] Attributes { get; } =
+ [
new ShaderVertexAttribute("aVertexPosition", ShaderVertexAttributeType.Float, 3, 0),
new ShaderVertexAttribute("aVertexTexCoord", ShaderVertexAttributeType.Float, 4, 12),
new ShaderVertexAttribute("aVertexTexMetadata", ShaderVertexAttributeType.Float, 2, 28),
- };
+ ];
}
}
diff --git a/OpenRA.Game/Graphics/RenderPostProcessPassVertex.cs b/OpenRA.Game/Graphics/RenderPostProcessPassVertex.cs
index 0bb501e49a..364b2c9c05 100644
--- a/OpenRA.Game/Graphics/RenderPostProcessPassVertex.cs
+++ b/OpenRA.Game/Graphics/RenderPostProcessPassVertex.cs
@@ -43,10 +43,10 @@ namespace OpenRA.Graphics
public RenderPostProcessPassShaderBindings(string name)
: base("postprocess", "postprocess_" + name) { }
- public override ShaderVertexAttribute[] Attributes { get; } = new[]
- {
+ public override ShaderVertexAttribute[] Attributes { get; } =
+ [
new ShaderVertexAttribute("aVertexPosition", ShaderVertexAttributeType.Float, 2, 0)
- };
+ ];
}
public sealed class RenderPostProcessPassTexturedShaderBindings : ShaderBindings
@@ -55,10 +55,10 @@ namespace OpenRA.Graphics
: base("postprocess_textured", "postprocess_textured_" + name)
{ }
- public override ShaderVertexAttribute[] Attributes { get; } = new[]
- {
+ public override ShaderVertexAttribute[] Attributes { get; } =
+ [
new ShaderVertexAttribute("aVertexPosition", ShaderVertexAttributeType.Float, 2, 0),
new ShaderVertexAttribute("aVertexTexCoord", ShaderVertexAttributeType.Float, 2, 8),
- };
+ ];
}
}
diff --git a/OpenRA.Game/Graphics/RgbaColorRenderer.cs b/OpenRA.Game/Graphics/RgbaColorRenderer.cs
index f2ceac5337..b36d2c3bca 100644
--- a/OpenRA.Game/Graphics/RgbaColorRenderer.cs
+++ b/OpenRA.Game/Graphics/RgbaColorRenderer.cs
@@ -191,7 +191,7 @@ namespace OpenRA.Graphics
{
var tr = new float3(br.X, tl.Y, tl.Z);
var bl = new float3(tl.X, br.Y, br.Z);
- DrawPolygon(new[] { tl, tr, br, bl }, width, color, blendMode);
+ DrawPolygon([tl, tr, br, bl], width, color, blendMode);
}
public void FillRect(in float3 tl, in float3 br, Color color, BlendMode blendMode = BlendMode.Alpha)
diff --git a/OpenRA.Game/Graphics/SheetBuilder.cs b/OpenRA.Game/Graphics/SheetBuilder.cs
index d38e76e5af..27721c91c0 100644
--- a/OpenRA.Game/Graphics/SheetBuilder.cs
+++ b/OpenRA.Game/Graphics/SheetBuilder.cs
@@ -33,7 +33,7 @@ namespace OpenRA.Graphics
public sealed class SheetBuilder : IDisposable
{
public readonly SheetType Type;
- readonly List sheets = new();
+ readonly List sheets = [];
readonly Func allocateSheet;
readonly int margin;
int rowHeight = 0;
diff --git a/OpenRA.Game/Graphics/SpriteCache.cs b/OpenRA.Game/Graphics/SpriteCache.cs
index c3e1e1391d..e75aa844ab 100644
--- a/OpenRA.Game/Graphics/SpriteCache.cs
+++ b/OpenRA.Game/Graphics/SpriteCache.cs
@@ -27,12 +27,12 @@ namespace OpenRA.Graphics
readonly Dictionary<
int,
- (int[] Frames, MiniYamlNode.SourceLocation Location, AdjustFrame AdjustFrame, bool Premultiplied)> spriteReservations = new();
- readonly Dictionary> reservationsByFilename = new();
+ (int[] Frames, MiniYamlNode.SourceLocation Location, AdjustFrame AdjustFrame, bool Premultiplied)> spriteReservations = [];
+ readonly Dictionary> reservationsByFilename = [];
- readonly Dictionary resolvedSprites = new();
+ readonly Dictionary resolvedSprites = [];
- readonly Dictionary missingFiles = new();
+ readonly Dictionary missingFiles = [];
int nextReservationToken = 1;
@@ -54,7 +54,7 @@ namespace OpenRA.Graphics
{
var token = nextReservationToken++;
spriteReservations[token] = (frames?.ToArray(), location, adjustFrame, premultiplied);
- reservationsByFilename.GetOrAdd(filename, _ => new List()).Add(token);
+ reservationsByFilename.GetOrAdd(filename, _ => []).Add(token);
return token;
}
diff --git a/OpenRA.Game/Graphics/SpriteRenderable.cs b/OpenRA.Game/Graphics/SpriteRenderable.cs
index f8a6cb03ff..32fb1ff924 100644
--- a/OpenRA.Game/Graphics/SpriteRenderable.cs
+++ b/OpenRA.Game/Graphics/SpriteRenderable.cs
@@ -9,7 +9,6 @@
*/
#endregion
-using System;
using System.Collections.Generic;
using OpenRA.Primitives;
@@ -17,7 +16,7 @@ namespace OpenRA.Graphics
{
public class SpriteRenderable : IPalettedRenderable, IModifyableRenderable, IFinalizedRenderable
{
- public static readonly IEnumerable None = Array.Empty();
+ public static readonly IEnumerable None = [];
readonly Sprite sprite;
readonly WPos pos;
diff --git a/OpenRA.Game/Graphics/TerrainSpriteLayer.cs b/OpenRA.Game/Graphics/TerrainSpriteLayer.cs
index 802e5e85b9..9efc2d65e9 100644
--- a/OpenRA.Game/Graphics/TerrainSpriteLayer.cs
+++ b/OpenRA.Game/Graphics/TerrainSpriteLayer.cs
@@ -19,7 +19,7 @@ namespace OpenRA.Graphics
public sealed class TerrainSpriteLayer : IDisposable
{
// PERF: we can reuse the IndexBuffer as all layers have the same size.
- static readonly ConditionalWeakTable IndexBuffers = new();
+ static readonly ConditionalWeakTable IndexBuffers = [];
readonly IndexBufferRc indexBufferWrapper;
public readonly BlendMode BlendMode;
@@ -30,7 +30,7 @@ namespace OpenRA.Graphics
readonly IVertexBuffer vertexBuffer;
readonly Vertex[] vertices;
readonly bool[] ignoreTint;
- readonly HashSet dirtyRows = new();
+ readonly HashSet dirtyRows = [];
readonly int indexRowStride;
readonly int vertexRowStride;
readonly bool restrictToBounds;
diff --git a/OpenRA.Game/Graphics/Util.cs b/OpenRA.Game/Graphics/Util.cs
index f8d6be32db..69d47b4f45 100644
--- a/OpenRA.Game/Graphics/Util.cs
+++ b/OpenRA.Game/Graphics/Util.cs
@@ -19,12 +19,12 @@ namespace OpenRA.Graphics
public static class Util
{
// yes, our channel order is nuts.
- static readonly int[] ChannelMasks = { 2, 1, 0, 3 };
+ static readonly int[] ChannelMasks = [2, 1, 0, 3];
public static uint[] CreateQuadIndices(int quads)
{
var indices = new uint[quads * 6];
- ReadOnlySpan cornerVertexMap = stackalloc uint[] { 0, 1, 2, 2, 3, 0 };
+ ReadOnlySpan cornerVertexMap = [0, 1, 2, 2, 3, 0];
for (var i = 0; i < indices.Length; i++)
indices[i] = cornerVertexMap[i % 6] + (uint)(4 * (i / 6));
@@ -277,13 +277,13 @@ namespace OpenRA.Graphics
size.X * angleSin - size.Y * angleCos,
(size.X * angleSin - size.Y * angleCos) * size.Z / size.Y);
- return new float3[]
- {
+ return
+ [
center - ra,
center + rb,
center + ra,
center - rb
- };
+ ];
}
///
diff --git a/OpenRA.Game/Graphics/Vertex.cs b/OpenRA.Game/Graphics/Vertex.cs
index 9e31c99279..0270e658aa 100644
--- a/OpenRA.Game/Graphics/Vertex.cs
+++ b/OpenRA.Game/Graphics/Vertex.cs
@@ -53,12 +53,12 @@ namespace OpenRA.Graphics
: base("combined")
{ }
- public override ShaderVertexAttribute[] Attributes { get; } = new[]
- {
+ public override ShaderVertexAttribute[] Attributes { get; } =
+ [
new ShaderVertexAttribute("aVertexPosition", ShaderVertexAttributeType.Float, 3, 0),
new ShaderVertexAttribute("aVertexTexCoord", ShaderVertexAttributeType.Float, 4, 12),
new ShaderVertexAttribute("aVertexAttributes", ShaderVertexAttributeType.UInt, 1, 28),
new ShaderVertexAttribute("aVertexTint", ShaderVertexAttributeType.Float, 4, 32)
- };
+ ];
}
}
diff --git a/OpenRA.Game/Graphics/WorldRenderer.cs b/OpenRA.Game/Graphics/WorldRenderer.cs
index 336d00e5d6..523a08f2ea 100644
--- a/OpenRA.Game/Graphics/WorldRenderer.cs
+++ b/OpenRA.Game/Graphics/WorldRenderer.cs
@@ -31,19 +31,19 @@ namespace OpenRA.Graphics
public event Action PaletteInvalidated = null;
- readonly HashSet onScreenActors = new();
+ readonly HashSet onScreenActors = [];
readonly HardwarePalette palette = new();
- readonly Dictionary palettes = new();
+ readonly Dictionary palettes = [];
readonly IRenderTerrain terrainRenderer;
readonly Lazy debugVis;
readonly Func createPaletteReference;
readonly bool enableDepthBuffer;
- readonly List preparedRenderables = new();
- readonly List preparedOverlayRenderables = new();
- readonly List preparedAnnotationRenderables = new();
+ readonly List preparedRenderables = [];
+ readonly List preparedOverlayRenderables = [];
+ readonly List preparedAnnotationRenderables = [];
- readonly List renderablesBuffer = new();
+ readonly List renderablesBuffer = [];
readonly IRenderer[] renderers;
readonly IRenderPostProcessPass[] postProcessPasses;
@@ -429,7 +429,7 @@ namespace OpenRA.Graphics
public float[] ScreenVector(in WVec vec)
{
var xyz = ScreenVectorComponents(vec);
- return new[] { xyz.X, xyz.Y, xyz.Z, 1f };
+ return [xyz.X, xyz.Y, xyz.Z, 1f];
}
public int2 ScreenPxOffset(in WVec vec)
diff --git a/OpenRA.Game/HotkeyDefinition.cs b/OpenRA.Game/HotkeyDefinition.cs
index 7775583892..5228d51bea 100644
--- a/OpenRA.Game/HotkeyDefinition.cs
+++ b/OpenRA.Game/HotkeyDefinition.cs
@@ -24,10 +24,10 @@ namespace OpenRA
[FluentReference]
public readonly string Description = "";
- public readonly HashSet Types = new();
+ public readonly HashSet Types = [];
[FluentReference]
- public readonly HashSet Contexts = new();
+ public readonly HashSet Contexts = [];
public readonly bool Readonly = false;
public bool HasDuplicates { get; internal set; }
diff --git a/OpenRA.Game/HotkeyManager.cs b/OpenRA.Game/HotkeyManager.cs
index a28f9266a3..825b3cbfe5 100644
--- a/OpenRA.Game/HotkeyManager.cs
+++ b/OpenRA.Game/HotkeyManager.cs
@@ -18,8 +18,8 @@ namespace OpenRA
public sealed class HotkeyManager
{
readonly Dictionary settings;
- readonly Dictionary definitions = new();
- readonly Dictionary keys = new();
+ readonly Dictionary definitions = [];
+ readonly Dictionary keys = [];
public HotkeyManager(IReadOnlyFileSystem fileSystem, Dictionary settings, Manifest manifest)
{
diff --git a/OpenRA.Game/Manifest.cs b/OpenRA.Game/Manifest.cs
index bb71c1ea8a..bdab33ebe0 100644
--- a/OpenRA.Game/Manifest.cs
+++ b/OpenRA.Game/Manifest.cs
@@ -78,11 +78,11 @@ namespace OpenRA
public readonly MiniYaml LoadScreen;
public readonly string DefaultOrderGenerator;
- public readonly string[] Assemblies = Array.Empty();
- public readonly string[] SoundFormats = Array.Empty();
- public readonly string[] SpriteFormats = Array.Empty();
- public readonly string[] PackageFormats = Array.Empty();
- public readonly string[] VideoFormats = Array.Empty();
+ public readonly string[] Assemblies = [];
+ public readonly string[] SoundFormats = [];
+ public readonly string[] SpriteFormats = [];
+ public readonly string[] PackageFormats = [];
+ public readonly string[] VideoFormats = [];
public readonly int FontSheetSize = 512;
public readonly int CursorSheetSize = 512;
@@ -91,15 +91,15 @@ namespace OpenRA
public readonly bool AllowUnusedFluentMessagesInExternalPackages = true;
readonly string[] reservedModuleNames =
- {
+ [
"Include", "Metadata", "FileSystem", "MapFolders", "Rules",
"Sequences", "ModelSequences", "Cursors", "Chrome", "Assemblies", "ChromeLayout", "Weapons",
"Voices", "Notifications", "Music", "FluentMessages", "TileSets", "ChromeMetrics", "Missions", "Hotkeys",
"ServerTraits", "LoadScreen", "DefaultOrderGenerator", "SupportsMapsFrom", "SoundFormats", "SpriteFormats", "VideoFormats",
"RequiresMods", "PackageFormats", "AllowUnusedFluentMessagesInExternalPackages", "FontSheetSize", "CursorSheetSize"
- };
+ ];
- readonly TypeDictionary modules = new();
+ readonly TypeDictionary modules = [];
readonly Dictionary yaml;
bool customDataLoaded;
@@ -127,7 +127,7 @@ namespace OpenRA
}
// Merge inherited overrides
- yaml = new MiniYaml(null, MiniYaml.Merge(new[] { nodes })).ToDictionary();
+ yaml = new MiniYaml(null, MiniYaml.Merge([nodes])).ToDictionary();
Metadata = FieldLoader.Load(yaml["Metadata"]);
@@ -207,11 +207,11 @@ namespace OpenRA
throw new InvalidDataException($"`{kv.Key}` is not a valid mod manifest entry.");
IGlobalModData module;
- var ctor = t.GetConstructor(new[] { typeof(MiniYaml) });
+ var ctor = t.GetConstructor([typeof(MiniYaml)]);
if (ctor != null)
{
// Class has opted-in to DIY initialization
- module = (IGlobalModData)ctor.Invoke(new object[] { kv.Value });
+ module = (IGlobalModData)ctor.Invoke([kv.Value]);
}
else
{
@@ -229,7 +229,7 @@ namespace OpenRA
static string[] YamlList(Dictionary yaml, string key)
{
if (!yaml.TryGetValue(key, out var value))
- return Array.Empty();
+ return [];
return value.Nodes.Select(n => n.Key).ToArray();
}
@@ -279,11 +279,11 @@ namespace OpenRA
}
IGlobalModData module;
- var ctor = t.GetConstructor(new[] { typeof(MiniYaml) });
+ var ctor = t.GetConstructor([typeof(MiniYaml)]);
if (ctor != null)
{
// Class has opted-in to DIY initialization
- module = (IGlobalModData)ctor.Invoke(new object[] { data.Value });
+ module = (IGlobalModData)ctor.Invoke([data.Value]);
}
else
{
diff --git a/OpenRA.Game/Map/ActorReference.cs b/OpenRA.Game/Map/ActorReference.cs
index 55e1b078f4..35c45cb968 100644
--- a/OpenRA.Game/Map/ActorReference.cs
+++ b/OpenRA.Game/Map/ActorReference.cs
@@ -74,11 +74,11 @@ namespace OpenRA
if (initInstance.Length > 1)
type.GetField(nameof(ActorInit.InstanceName)).SetValue(init, initInstance[1]);
- var loader = type.GetMethod("Initialize", new[] { typeof(MiniYaml) });
+ var loader = type.GetMethod("Initialize", [typeof(MiniYaml)]);
if (loader == null)
throw new InvalidDataException($"{initInstance[0]}Init does not define a yaml-assignable type.");
- loader.Invoke(init, new[] { initYaml });
+ loader.Invoke(init, [initYaml]);
return init;
}
diff --git a/OpenRA.Game/Map/Map.cs b/OpenRA.Game/Map/Map.cs
index 64f4b6a2c6..937a2dc2ab 100644
--- a/OpenRA.Game/Map/Map.cs
+++ b/OpenRA.Game/Map/Map.cs
@@ -11,7 +11,6 @@
using System;
using System.Collections.Generic;
-using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -158,7 +157,7 @@ namespace OpenRA
/// Defines the order of the fields in map.yaml.
static readonly MapField[] YamlFields =
- {
+ [
new("MapFormat"),
new("RequiresMod"),
new("Title"),
@@ -179,7 +178,7 @@ namespace OpenRA
new("Voices", nameof(VoiceDefinitions), required: false),
new("Music", nameof(MusicDefinitions), required: false),
new("Notifications", nameof(NotificationDefinitions), required: false),
- };
+ ];
// Format versions
public int MapFormat { get; private set; }
@@ -193,13 +192,13 @@ namespace OpenRA
public bool LockPreview;
public Rectangle Bounds;
public MapVisibility Visibility = MapVisibility.Lobby;
- public string[] Categories = { "Conquest" };
+ public string[] Categories = ["Conquest"];
public int2 MapSize { get; private set; }
// Player and actor yaml. Public for access by the map importers and lint checks.
- public IReadOnlyCollection PlayerDefinitions = ImmutableArray.Empty;
- public IReadOnlyCollection ActorDefinitions = ImmutableArray.Empty;
+ public IReadOnlyCollection PlayerDefinitions = [];
+ public IReadOnlyCollection ActorDefinitions = [];
// Custom map yaml. Public for access by the map importers and lint checks
public MiniYaml RuleDefinitions;
@@ -211,7 +210,7 @@ namespace OpenRA
public MiniYaml MusicDefinitions;
public MiniYaml NotificationDefinitions;
- public readonly Dictionary ReplacedInvalidTerrainTiles = new();
+ public readonly Dictionary ReplacedInvalidTerrainTiles = [];
// Generated data
public readonly MapGrid Grid;
@@ -283,7 +282,7 @@ namespace OpenRA
// Take the SHA1
if (streams.Count == 0)
- return CryptoUtil.SHA1Hash(Array.Empty());
+ return CryptoUtil.SHA1Hash([]);
var merged = streams[0];
for (var i = 1; i < streams.Count; i++)
@@ -368,8 +367,8 @@ namespace OpenRA
if (MapFormat < SupportedMapFormat)
throw new InvalidDataException($"Map format {MapFormat} is not supported.\n File: {package.Name}");
- PlayerDefinitions = yaml.NodeWithKeyOrDefault("Players")?.Value.Nodes ?? ImmutableArray.Empty;
- ActorDefinitions = yaml.NodeWithKeyOrDefault("Actors")?.Value.Nodes ?? ImmutableArray.Empty;
+ PlayerDefinitions = yaml.NodeWithKeyOrDefault("Players")?.Value.Nodes ?? [];
+ ActorDefinitions = yaml.NodeWithKeyOrDefault("Actors")?.Value.Nodes ?? [];
Grid = modData.Manifest.Get();
@@ -516,7 +515,7 @@ namespace OpenRA
foreach (var cell in AllCells)
{
var uv = cell.ToMPos(Grid.Type);
- cellProjection[uv] = Array.Empty();
+ cellProjection[uv] = [];
inverseCellProjection[uv] = new List(1);
}
@@ -532,7 +531,7 @@ namespace OpenRA
if (Grid.MaximumTerrainHeight == 0)
{
uv = cell.ToMPos(Grid.Type);
- cellProjection[cell] = new[] { (PPos)uv };
+ cellProjection[cell] = [(PPos)uv];
var inverse = inverseCellProjection[uv];
inverse.Clear();
inverse.Add(uv);
@@ -607,7 +606,7 @@ namespace OpenRA
// Any changes to this function should be reflected when setting projectionSafeBounds.
var height = mapHeight[uv];
if (height == 0)
- return new[] { (PPos)uv };
+ return [(PPos)uv];
// Odd-height ramps get bumped up a level to the next even height layer
if ((height & 1) == 1 && Ramp[uv] != 0)
@@ -1044,7 +1043,7 @@ namespace OpenRA
return (PPos)CellContaining(projectedPos).ToMPos(Grid.Type);
}
- static readonly PPos[] NoProjectedCells = Array.Empty();
+ static readonly PPos[] NoProjectedCells = [];
public PPos[] ProjectedCellsCovering(MPos uv)
{
if (!initializedCellProjection)
@@ -1064,7 +1063,7 @@ namespace OpenRA
InitializeCellProjection();
if (!inverseCellProjection.Contains(uv))
- return new List();
+ return [];
return inverseCellProjection[uv];
}
diff --git a/OpenRA.Game/Map/MapCache.cs b/OpenRA.Game/Map/MapCache.cs
index d79ff28a0b..b58ceb2f02 100644
--- a/OpenRA.Game/Map/MapCache.cs
+++ b/OpenRA.Game/Map/MapCache.cs
@@ -28,7 +28,7 @@ namespace OpenRA
{
public static readonly MapPreview UnknownMap = new(null, null, MapGridType.Rectangular, null);
public IReadOnlyDictionary MapLocations => mapLocations;
- readonly Dictionary mapLocations = new();
+ readonly Dictionary mapLocations = [];
public bool LoadPreviewImages = true;
readonly Cache previews;
@@ -37,17 +37,17 @@ namespace OpenRA
Thread previewLoaderThread;
bool previewLoaderThreadShutDown = true;
readonly object syncRoot = new();
- readonly Queue generateMinimap = new();
+ readonly Queue generateMinimap = [];
- public HashSet StringPool { get; } = new();
+ public HashSet StringPool { get; } = [];
- readonly List mapDirectoryTrackers = new();
+ readonly List mapDirectoryTrackers = [];
///
/// The most recently modified or loaded map at runtime.
///
public string LastModifiedMap { get; private set; } = null;
- readonly Dictionary mapUpdates = new();
+ readonly Dictionary mapUpdates = [];
string lastLoadedLastModifiedMap;
diff --git a/OpenRA.Game/Map/MapDirectoryTracker.cs b/OpenRA.Game/Map/MapDirectoryTracker.cs
index 04c75c23cf..171c0dfbe9 100644
--- a/OpenRA.Game/Map/MapDirectoryTracker.cs
+++ b/OpenRA.Game/Map/MapDirectoryTracker.cs
@@ -24,7 +24,7 @@ namespace OpenRA
readonly MapClassification classification;
enum MapAction { Add, Delete, Update }
- readonly Dictionary mapActionQueue = new();
+ readonly Dictionary mapActionQueue = [];
bool dirty = false;
diff --git a/OpenRA.Game/Map/MapGrid.cs b/OpenRA.Game/Map/MapGrid.cs
index cfa13b2d22..a44bbd8211 100644
--- a/OpenRA.Game/Map/MapGrid.cs
+++ b/OpenRA.Game/Map/MapGrid.cs
@@ -37,43 +37,43 @@ namespace OpenRA
Orientation = orientation;
if (type == MapGridType.RectangularIsometric)
{
- Corners = new[]
- {
+ Corners =
+ [
new WVec(0, -724, 724 * (int)tl),
new WVec(724, 0, 724 * (int)tr),
new WVec(0, 724, 724 * (int)br),
new WVec(-724, 0, 724 * (int)bl),
- };
+ ];
}
else
{
- Corners = new[]
- {
+ Corners =
+ [
new WVec(-512, -512, 512 * (int)tl),
new WVec(512, -512, 512 * (int)tr),
new WVec(512, 512, 512 * (int)br),
new WVec(-512, 512, 512 * (int)bl)
- };
+ ];
}
if (split == RampSplit.X)
{
- Polygons = new[]
- {
- new[] { Corners[0], Corners[1], Corners[3] },
- new[] { Corners[1], Corners[2], Corners[3] }
- };
+ Polygons =
+ [
+ [Corners[0], Corners[1], Corners[3]],
+ [Corners[1], Corners[2], Corners[3]]
+ ];
}
else if (split == RampSplit.Y)
{
- Polygons = new[]
- {
- new[] { Corners[0], Corners[1], Corners[2] },
- new[] { Corners[0], Corners[2], Corners[3] }
- };
+ Polygons =
+ [
+ [Corners[0], Corners[1], Corners[2]],
+ [Corners[0], Corners[2], Corners[3]]
+ ];
}
else
- Polygons = new[] { Corners };
+ Polygons = [Corners];
// Initial value must be assigned before HeightOffset can be called
CenterHeightOffset = 0;
@@ -115,14 +115,14 @@ namespace OpenRA
public readonly bool EnableDepthBuffer = false;
public readonly WVec[] SubCellOffsets =
- {
+ [
new(0, 0, 0), // full cell - index 0
new(-299, -256, 0), // top left - index 1
new(256, -256, 0), // top right - index 2
new(0, 0, 0), // center - index 3
new(-299, 256, 0), // bottom left - index 4
new(256, 256, 0), // bottom right - index 5
- };
+ ];
public CellRamp[] Ramps { get; }
@@ -159,8 +159,9 @@ namespace OpenRA
var halfBackward = -halfForward;
// Slope types are hardcoded following the convention from the TS and RA2 map format
- Ramps = new[]
- {
+ Ramps =
+ [
+
// Flat
new CellRamp(Type, WRot.None),
@@ -193,7 +194,7 @@ namespace OpenRA
new CellRamp(Type, WRot.None, tl: RampCornerHeight.Half, br: RampCornerHeight.Half, split: RampSplit.Y),
new CellRamp(Type, WRot.None, tr: RampCornerHeight.Half, bl: RampCornerHeight.Half, split: RampSplit.X),
new CellRamp(Type, WRot.None, tl: RampCornerHeight.Half, br: RampCornerHeight.Half, split: RampSplit.X),
- };
+ ];
TilesByDistance = CreateTilesByDistance();
}
@@ -202,7 +203,7 @@ namespace OpenRA
{
var ts = new List[MaximumTileSearchRange + 1];
for (var i = 0; i < MaximumTileSearchRange + 1; i++)
- ts[i] = new List();
+ ts[i] = [];
for (var j = -MaximumTileSearchRange; j <= MaximumTileSearchRange; j++)
for (var i = -MaximumTileSearchRange; i <= MaximumTileSearchRange; i++)
diff --git a/OpenRA.Game/Map/MapPlayers.cs b/OpenRA.Game/Map/MapPlayers.cs
index caf5108d18..7e26d1549c 100644
--- a/OpenRA.Game/Map/MapPlayers.cs
+++ b/OpenRA.Game/Map/MapPlayers.cs
@@ -24,7 +24,7 @@ namespace OpenRA
public readonly Dictionary Players;
public MapPlayers()
- : this(new List()) { }
+ : this([]) { }
public MapPlayers(IEnumerable playerDefinitions)
{
@@ -66,7 +66,7 @@ namespace OpenRA
Name = $"Multi{index}",
Faction = "Random",
Playable = true,
- Enemies = new[] { "Creeps" }
+ Enemies = ["Creeps"]
};
Players.Add(p.Name, p);
}
diff --git a/OpenRA.Game/Map/MapPreview.cs b/OpenRA.Game/Map/MapPreview.cs
index a22830ddbe..f5dd1a9a85 100644
--- a/OpenRA.Game/Map/MapPreview.cs
+++ b/OpenRA.Game/Map/MapPreview.cs
@@ -51,7 +51,7 @@ namespace OpenRA
public readonly string[] categories;
public readonly int players;
public readonly Rectangle bounds;
- public readonly short[] spawnpoints = Array.Empty();
+ public readonly short[] spawnpoints = [];
public readonly MapGridType map_grid_type;
public readonly string minimap;
public readonly bool downloading;
@@ -195,7 +195,7 @@ namespace OpenRA
}
}
- static readonly CPos[] NoSpawns = Array.Empty();
+ static readonly CPos[] NoSpawns = [];
readonly MapCache cache;
readonly ModData modData;
IReadOnlyPackage package;
@@ -321,7 +321,7 @@ namespace OpenRA
{
MapFormat = 0,
Title = "Unknown Map",
- Categories = new[] { "Unknown" },
+ Categories = ["Unknown"],
Author = "Unknown Author",
TileSet = "unknown",
Players = null,
@@ -421,11 +421,11 @@ namespace OpenRA
newData.SpawnPoints = spawns.ToArray();
}
else
- newData.SpawnPoints = Array.Empty();
+ newData.SpawnPoints = [];
}
catch (Exception)
{
- newData.SpawnPoints = Array.Empty();
+ newData.SpawnPoints = [];
newData.Status = MapStatus.Unavailable;
}
diff --git a/OpenRA.Game/Map/PlayerReference.cs b/OpenRA.Game/Map/PlayerReference.cs
index 5c3a4beae7..b01b43937f 100644
--- a/OpenRA.Game/Map/PlayerReference.cs
+++ b/OpenRA.Game/Map/PlayerReference.cs
@@ -9,7 +9,6 @@
*/
#endregion
-using System;
using OpenRA.Primitives;
namespace OpenRA
@@ -54,8 +53,8 @@ namespace OpenRA
public bool LockHandicap = false;
public int Handicap = 0;
- public string[] Allies = Array.Empty();
- public string[] Enemies = Array.Empty();
+ public string[] Allies = [];
+ public string[] Enemies = [];
public PlayerReference() { }
public PlayerReference(MiniYaml my) { FieldLoader.Load(this, my); }
diff --git a/OpenRA.Game/Map/TerrainInfo.cs b/OpenRA.Game/Map/TerrainInfo.cs
index 24b3d12fd0..090033e1eb 100644
--- a/OpenRA.Game/Map/TerrainInfo.cs
+++ b/OpenRA.Game/Map/TerrainInfo.cs
@@ -60,7 +60,7 @@ namespace OpenRA
{
public readonly string Type;
public readonly BitSet TargetTypes;
- public readonly HashSet AcceptsSmudgeType = new();
+ public readonly HashSet AcceptsSmudgeType = [];
public readonly Color Color;
public readonly bool RestrictPlayerColor = false;
diff --git a/OpenRA.Game/MiniYaml.cs b/OpenRA.Game/MiniYaml.cs
index 2b534bc1ee..d368190f18 100644
--- a/OpenRA.Game/MiniYaml.cs
+++ b/OpenRA.Game/MiniYaml.cs
@@ -99,7 +99,7 @@ namespace OpenRA
}
public MiniYamlNode(string k, string v, string c = null)
- : this(k, new MiniYaml(v, Enumerable.Empty()), c) { }
+ : this(k, new MiniYaml(v, []), c) { }
public MiniYamlNode(string k, string v, IEnumerable n)
: this(k, new MiniYaml(v, n), null) { }
@@ -115,7 +115,7 @@ namespace OpenRA
const int SpacesPerLevel = 4;
static readonly Func StringIdentity = s => s;
static readonly Func MiniYamlIdentity = my => my;
- static readonly Dictionary ConflictScratch = new();
+ static readonly Dictionary ConflictScratch = [];
public readonly string Value;
public readonly ImmutableArray Nodes;
@@ -196,12 +196,12 @@ namespace OpenRA
}
public MiniYaml(string value)
- : this(value, Enumerable.Empty()) { }
+ : this(value, []) { }
public MiniYaml(string value, IEnumerable nodes)
{
Value = value;
- Nodes = ImmutableArray.CreateRange(nodes);
+ Nodes = nodes.ToImmutableArray();
}
static List FromLines(IEnumerable> lines, string name, bool discardCommentsAndWhitespace, HashSet stringPool)
@@ -210,7 +210,7 @@ namespace OpenRA
// Pool these strings so we only need one copy of each unique string.
// This saves on long-term memory usage as parsed values can often live a long time.
// A caller can also provide a pool as input, allowing de-duplication across multiple parses.
- stringPool ??= new HashSet();
+ stringPool ??= [];
var result = new List>
{
@@ -352,7 +352,7 @@ namespace OpenRA
{
var lastLevel = parsedLines[^1].Level;
while (lastLevel >= result.Count)
- result.Add(new List());
+ result.Add([]);
while (parsedLines.Count > 0 && parsedLines[^1].Level >= level)
{
@@ -393,14 +393,14 @@ namespace OpenRA
public static List FromString(string text, string name, bool discardCommentsAndWhitespace = true, HashSet stringPool = null)
{
- return FromLines(text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None).Select(s => s.AsMemory()), name, discardCommentsAndWhitespace, stringPool);
+ return FromLines(text.Split(["\r\n", "\n"], StringSplitOptions.None).Select(s => s.AsMemory()), name, discardCommentsAndWhitespace, stringPool);
}
public static List Merge(IEnumerable> sources)
{
var sourcesList = sources.ToList();
if (sourcesList.Count == 0)
- return new List();
+ return [];
var tree = sourcesList
.Where(s => s != null)
@@ -696,7 +696,7 @@ namespace OpenRA
public MiniYamlBuilder(string value, List nodes)
{
Value = value;
- Nodes = nodes == null ? new List() : nodes.ConvertAll(x => new MiniYamlNodeBuilder(x));
+ Nodes = nodes == null ? [] : nodes.ConvertAll(x => new MiniYamlNodeBuilder(x));
}
public MiniYaml Build()
diff --git a/OpenRA.Game/ModData.cs b/OpenRA.Game/ModData.cs
index 32a7ffc15f..6cb0ec8b98 100644
--- a/OpenRA.Game/ModData.cs
+++ b/OpenRA.Game/ModData.cs
@@ -49,7 +49,7 @@ namespace OpenRA
public ModData(Manifest mod, InstalledMods mods, bool useLoadScreen = false)
{
- Languages = Array.Empty();
+ Languages = [];
// Take a local copy of the manifest
Manifest = new Manifest(mod.Id, mod.Package);
@@ -82,19 +82,19 @@ namespace OpenRA
var terrainFormat = Manifest.Get();
var terrainLoader = ObjectCreator.FindType(terrainFormat.Type + "Loader");
- var terrainCtor = terrainLoader?.GetConstructor(new[] { typeof(ModData) });
+ var terrainCtor = terrainLoader?.GetConstructor([typeof(ModData)]);
if (terrainLoader == null || !terrainLoader.GetInterfaces().Contains(typeof(ITerrainLoader)) || terrainCtor == null)
throw new InvalidOperationException($"Unable to find a terrain loader for type '{terrainFormat.Type}'.");
- TerrainLoader = (ITerrainLoader)terrainCtor.Invoke(new[] { this });
+ TerrainLoader = (ITerrainLoader)terrainCtor.Invoke([this]);
var sequenceFormat = Manifest.Get();
var sequenceLoader = ObjectCreator.FindType(sequenceFormat.Type + "Loader");
- var sequenceCtor = sequenceLoader?.GetConstructor(new[] { typeof(ModData) });
+ var sequenceCtor = sequenceLoader?.GetConstructor([typeof(ModData)]);
if (sequenceLoader == null || !sequenceLoader.GetInterfaces().Contains(typeof(ISpriteSequenceLoader)) || sequenceCtor == null)
throw new InvalidOperationException($"Unable to find a sequence loader for type '{sequenceFormat.Type}'.");
- SpriteSequenceLoader = (ISpriteSequenceLoader)sequenceCtor.Invoke(new[] { this });
+ SpriteSequenceLoader = (ISpriteSequenceLoader)sequenceCtor.Invoke([this]);
Hotkeys = new HotkeyManager(ModFiles, Game.Settings.Keys, Manifest);
diff --git a/OpenRA.Game/Network/Connection.cs b/OpenRA.Game/Network/Connection.cs
index 9063ce80b3..6bc57a16b2 100644
--- a/OpenRA.Game/Network/Connection.cs
+++ b/OpenRA.Game/Network/Connection.cs
@@ -42,9 +42,9 @@ namespace OpenRA.Network
public sealed class EchoConnection : IConnection
{
const int LocalClientId = 1;
- readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sync = new();
- readonly Queue<(int Frame, OrderPacket Orders)> orders = new();
- readonly Queue immediateOrders = new();
+ readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sync = [];
+ readonly Queue<(int Frame, OrderPacket Orders)> orders = [];
+ readonly Queue immediateOrders = [];
bool disposed;
int IConnection.LocalClientId => LocalClientId;
@@ -52,7 +52,7 @@ namespace OpenRA.Network
void IConnection.StartGame()
{
// Inject an empty frame to fill the gap we are making by projecting forward orders
- orders.Enqueue((0, new OrderPacket(Array.Empty())));
+ orders.Enqueue((0, new OrderPacket([])));
}
void IConnection.Send(int frame, IEnumerable o)
@@ -100,12 +100,12 @@ namespace OpenRA.Network
{
public readonly ConnectionTarget Target;
internal ReplayRecorder Recorder { get; private set; }
- readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sentSync = new();
- readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> queuedSyncPackets = new();
+ readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> sentSync = [];
+ readonly Queue<(int Frame, int SyncHash, ulong DefeatState)> queuedSyncPackets = [];
- readonly Queue<(int Frame, OrderPacket Orders)> sentOrders = new();
- readonly Queue sentImmediateOrders = new();
- readonly ConcurrentQueue<(int FromClient, byte[] Data)> receivedPackets = new();
+ readonly Queue<(int Frame, OrderPacket Orders)> sentOrders = [];
+ readonly Queue sentImmediateOrders = [];
+ readonly ConcurrentQueue<(int FromClient, byte[] Data)> receivedPackets = [];
TcpClient tcp;
volatile ConnectionState connectionState = ConnectionState.Connecting;
volatile int clientId;
diff --git a/OpenRA.Game/Network/ConnectionTarget.cs b/OpenRA.Game/Network/ConnectionTarget.cs
index 53b153b70e..3ff70b223f 100644
--- a/OpenRA.Game/Network/ConnectionTarget.cs
+++ b/OpenRA.Game/Network/ConnectionTarget.cs
@@ -22,12 +22,12 @@ namespace OpenRA.Network
public ConnectionTarget()
{
- endpoints = new[] { new DnsEndPoint("invalid", 0) };
+ endpoints = [new DnsEndPoint("invalid", 0)];
}
public ConnectionTarget(string host, int port)
{
- endpoints = new[] { new DnsEndPoint(host, port) };
+ endpoints = [new DnsEndPoint(host, port)];
}
public ConnectionTarget(IEnumerable endpoints)
@@ -48,7 +48,7 @@ namespace OpenRA.Network
}
catch (Exception)
{
- return Enumerable.Empty();
+ return [];
}
}).ToList();
}
diff --git a/OpenRA.Game/Network/GameSave.cs b/OpenRA.Game/Network/GameSave.cs
index 29f8a3a224..85ffdaad8f 100644
--- a/OpenRA.Game/Network/GameSave.cs
+++ b/OpenRA.Game/Network/GameSave.cs
@@ -86,22 +86,22 @@ namespace OpenRA.Network
// Loaded from file and updated during gameplay
public int LastOrdersFrame { get; private set; }
public int LastSyncFrame { get; private set; }
- byte[] lastSyncPacket = Array.Empty();
+ byte[] lastSyncPacket = [];
// Loaded from file or set on game start
public Session.Global GlobalSettings { get; private set; }
public Dictionary Slots { get; private set; }
public Dictionary SlotClients { get; private set; }
- public Dictionary TraitData = new();
+ public Dictionary TraitData = [];
// Set on game start
- int[] clientsBySlotIndex = Array.Empty();
+ int[] clientsBySlotIndex = [];
int firstBotSlotIndex = -1;
public GameSave()
{
LastOrdersFrame = -1;
- Slots = new Dictionary();
+ Slots = [];
}
public GameSave(string filepath)
@@ -126,7 +126,7 @@ namespace OpenRA.Network
GlobalSettings = Session.Global.Deserialize(globalSettings[0].Value);
var slots = MiniYaml.FromString(rs.ReadLengthPrefixedString(Encoding.UTF8, Connection.MaxOrderLength), $"{filepath}:slots");
- Slots = new Dictionary();
+ Slots = [];
foreach (var s in slots)
{
var slot = Session.Slot.Deserialize(s.Value);
@@ -134,7 +134,7 @@ namespace OpenRA.Network
}
var slotClients = MiniYaml.FromString(rs.ReadLengthPrefixedString(Encoding.UTF8, Connection.MaxOrderLength), $"{filepath}:slotClients");
- SlotClients = new Dictionary();
+ SlotClients = [];
foreach (var s in slotClients)
{
var slotClient = SlotClient.Deserialize(s.Value);
@@ -166,8 +166,8 @@ namespace OpenRA.Network
// Perform a deep clone by round-tripping the data
GlobalSettings = Session.Global.Deserialize(lobbyInfo.GlobalSettings.Serialize().Value);
- Slots = new Dictionary();
- SlotClients = new Dictionary();
+ Slots = [];
+ SlotClients = [];
foreach (var s in lobbyInfo.Slots)
{
Slots[s.Key] = Session.Slot.Deserialize(s.Value.Serialize().Value);
diff --git a/OpenRA.Game/Network/GameServer.cs b/OpenRA.Game/Network/GameServer.cs
index ce4fe4f3e3..0c335e1a53 100644
--- a/OpenRA.Game/Network/GameServer.cs
+++ b/OpenRA.Game/Network/GameServer.cs
@@ -48,7 +48,8 @@ namespace OpenRA.Network
public class GameServer
{
static readonly string[] SerializeFields =
- {
+ [
+
// Server information
"Name", "Address",
@@ -57,7 +58,7 @@ namespace OpenRA.Network
// Current server state
"Map", "State", "MaxPlayers", "Protected", "Authentication", "DisabledSpawnPoints"
- };
+ ];
public const int ProtocolVersion = 2;
@@ -133,7 +134,7 @@ namespace OpenRA.Network
public readonly GameClient[] Clients;
/// The list of spawnpoints that are disabled for this game.
- public readonly int[] DisabledSpawnPoints = Array.Empty();
+ public readonly int[] DisabledSpawnPoints = [];
public string ModLabel => $"{ModTitle} ({Version})";
@@ -228,7 +229,7 @@ namespace OpenRA.Network
Protected = !string.IsNullOrEmpty(server.Settings.Password);
Authentication = server.Settings.RequireAuthentication || server.Settings.ProfileIDWhitelist.Length > 0;
Clients = server.LobbyInfo.Clients.Select(c => new GameClient(c)).ToArray();
- DisabledSpawnPoints = server.LobbyInfo.DisabledSpawnPoints?.ToArray() ?? Array.Empty();
+ DisabledSpawnPoints = server.LobbyInfo.DisabledSpawnPoints?.ToArray() ?? [];
}
public string ToPOSTData(bool lanGame)
diff --git a/OpenRA.Game/Network/OrderIO.cs b/OpenRA.Game/Network/OrderIO.cs
index afb587ab79..0366f96d84 100644
--- a/OpenRA.Game/Network/OrderIO.cs
+++ b/OpenRA.Game/Network/OrderIO.cs
@@ -78,7 +78,7 @@ namespace OpenRA.Network
public static class OrderIO
{
- static readonly OrderPacket NoOrders = new(Array.Empty());
+ static readonly OrderPacket NoOrders = new([]);
public static byte[] SerializeSync((int Frame, int SyncHash, ulong DefeatState) data)
{
diff --git a/OpenRA.Game/Network/OrderManager.cs b/OpenRA.Game/Network/OrderManager.cs
index f955d7804c..5f8ec3d701 100644
--- a/OpenRA.Game/Network/OrderManager.cs
+++ b/OpenRA.Game/Network/OrderManager.cs
@@ -26,8 +26,8 @@ namespace OpenRA.Network
const string DesyncCompareLogs = "notification-desync-compare-logs";
readonly SyncReport syncReport;
- readonly Dictionary> pendingOrders = new();
- readonly Dictionary syncForFrame = new();
+ readonly Dictionary> pendingOrders = [];
+ readonly Dictionary syncForFrame = [];
public Session LobbyInfo = new();
@@ -53,11 +53,11 @@ namespace OpenRA.Network
internal int GameSaveLastFrame = -1;
internal int GameSaveLastSyncFrame = -1;
- readonly List localOrders = new();
- readonly List localImmediateOrders = new();
+ readonly List localOrders = [];
+ readonly List localImmediateOrders = [];
- readonly List processClientOrders = new();
- readonly List