diff options
author | Jesse Plamondon-Willard <Pathoschild@users.noreply.github.com> | 2022-04-06 18:24:59 -0400 |
---|---|---|
committer | Jesse Plamondon-Willard <Pathoschild@users.noreply.github.com> | 2022-04-06 18:24:59 -0400 |
commit | a593eda30f82af474887d91458b0e9158f66fefc (patch) | |
tree | 8aa0e0586e3cce7627e8c4ff445a953665953f8f | |
parent | 29f909a8d5dbb83d6df1a54d2680e6f9898f3b19 (diff) | |
download | SMAPI-a593eda30f82af474887d91458b0e9158f66fefc.tar.gz SMAPI-a593eda30f82af474887d91458b0e9158f66fefc.tar.bz2 SMAPI-a593eda30f82af474887d91458b0e9158f66fefc.zip |
use target-typed new
83 files changed, 203 insertions, 203 deletions
diff --git a/src/SMAPI.Installer/Framework/InstallerContext.cs b/src/SMAPI.Installer/Framework/InstallerContext.cs index bb973230..abc7adde 100644 --- a/src/SMAPI.Installer/Framework/InstallerContext.cs +++ b/src/SMAPI.Installer/Framework/InstallerContext.cs @@ -12,7 +12,7 @@ namespace StardewModdingAPI.Installer.Framework ** Fields *********/ /// <summary>The underlying toolkit game scanner.</summary> - private readonly GameScanner GameScanner = new GameScanner(); + private readonly GameScanner GameScanner = new(); /********* diff --git a/src/SMAPI.Installer/InteractiveInstaller.cs b/src/SMAPI.Installer/InteractiveInstaller.cs index b3bba883..a126c3b8 100644 --- a/src/SMAPI.Installer/InteractiveInstaller.cs +++ b/src/SMAPI.Installer/InteractiveInstaller.cs @@ -126,7 +126,7 @@ namespace StardewModdingApi.Installer /**** ** Get basic info & set window title ****/ - ModToolkit toolkit = new ModToolkit(); + ModToolkit toolkit = new(); var context = new InstallerContext(); Console.Title = $"SMAPI {context.GetInstallerVersion()} installer on {context.Platform} {context.PlatformName}"; Console.WriteLine(); @@ -246,7 +246,7 @@ namespace StardewModdingApi.Installer } // get folders - DirectoryInfo bundleDir = new DirectoryInfo(this.BundlePath); + DirectoryInfo bundleDir = new(this.BundlePath); paths = new InstallerPaths(bundleDir, installDir); } @@ -354,8 +354,8 @@ namespace StardewModdingApi.Installer // move global save data folder (changed in 3.2) { string dataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley"); - DirectoryInfo oldDir = new DirectoryInfo(Path.Combine(dataPath, "Saves", ".smapi")); - DirectoryInfo newDir = new DirectoryInfo(Path.Combine(dataPath, ".smapi")); + DirectoryInfo oldDir = new(Path.Combine(dataPath, "Saves", ".smapi")); + DirectoryInfo newDir = new(Path.Combine(dataPath, ".smapi")); if (oldDir.Exists) { @@ -428,7 +428,7 @@ namespace StardewModdingApi.Installer } // add or replace bundled mods - DirectoryInfo bundledModsDir = new DirectoryInfo(Path.Combine(paths.BundlePath, "Mods")); + DirectoryInfo bundledModsDir = new(Path.Combine(paths.BundlePath, "Mods")); if (bundledModsDir.Exists && bundledModsDir.EnumerateDirectories().Any()) { this.PrintDebug("Adding bundled mods..."); @@ -450,7 +450,7 @@ namespace StardewModdingApi.Installer // find target folder ModFolder targetMod = targetMods.FirstOrDefault(p => p.Manifest?.UniqueID?.Equals(sourceMod.Manifest.UniqueID, StringComparison.OrdinalIgnoreCase) == true); - DirectoryInfo defaultTargetFolder = new DirectoryInfo(Path.Combine(paths.ModsPath, sourceMod.Directory.Name)); + DirectoryInfo defaultTargetFolder = new(Path.Combine(paths.ModsPath, sourceMod.Directory.Name)); DirectoryInfo targetFolder = targetMod?.Directory ?? defaultTargetFolder; this.PrintDebug(targetFolder.FullName == defaultTargetFolder.FullName ? $" adding {sourceMod.Manifest.Name}..." @@ -593,7 +593,7 @@ namespace StardewModdingApi.Installer break; case DirectoryInfo sourceDir: - DirectoryInfo targetSubfolder = new DirectoryInfo(Path.Combine(targetFolder.FullName, sourceDir.Name)); + DirectoryInfo targetSubfolder = new(Path.Combine(targetFolder.FullName, sourceDir.Name)); foreach (var entry in sourceDir.EnumerateFileSystemInfos()) this.RecursiveCopy(entry, targetSubfolder, filter); break; @@ -717,7 +717,7 @@ namespace StardewModdingApi.Installer // get directory if (File.Exists(path)) path = Path.GetDirectoryName(path); - DirectoryInfo directory = new DirectoryInfo(path); + DirectoryInfo directory = new(path); // validate path if (!directory.Exists) @@ -795,7 +795,7 @@ namespace StardewModdingApi.Installer // get path string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley"); - DirectoryInfo modDir = new DirectoryInfo(Path.Combine(appDataPath, "Mods")); + DirectoryInfo modDir = new(Path.Combine(appDataPath, "Mods")); // check if migration needed if (!modDir.Exists) diff --git a/src/SMAPI.Installer/Program.cs b/src/SMAPI.Installer/Program.cs index 45cfea75..2c9b2c0a 100644 --- a/src/SMAPI.Installer/Program.cs +++ b/src/SMAPI.Installer/Program.cs @@ -31,7 +31,7 @@ namespace StardewModdingApi.Installer public static void Main(string[] args) { // find install bundle - FileInfo zipFile = new FileInfo(Path.Combine(Program.InstallerPath, "install.dat")); + FileInfo zipFile = new(Path.Combine(Program.InstallerPath, "install.dat")); if (!zipFile.Exists) { Console.WriteLine($"Oops! Some of the installer files are missing; try re-downloading the installer. (Missing file: {zipFile.FullName})"); @@ -40,7 +40,7 @@ namespace StardewModdingApi.Installer } // unzip bundle into temp folder - DirectoryInfo bundleDir = new DirectoryInfo(Program.ExtractedBundlePath); + DirectoryInfo bundleDir = new(Program.ExtractedBundlePath); Console.WriteLine("Extracting install files..."); ZipFile.ExtractToDirectory(zipFile.FullName, bundleDir.FullName); @@ -70,7 +70,7 @@ namespace StardewModdingApi.Installer { try { - AssemblyName name = new AssemblyName(e.Name); + AssemblyName name = new(e.Name); foreach (FileInfo dll in new DirectoryInfo(Program.InternalFilesPath).EnumerateFiles("*.dll")) { if (name.Name.Equals(AssemblyName.GetAssemblyName(dll.FullName).Name, StringComparison.OrdinalIgnoreCase)) diff --git a/src/SMAPI.Internal.Patching/HarmonyPatcher.cs b/src/SMAPI.Internal.Patching/HarmonyPatcher.cs index c07e3b41..6f30c241 100644 --- a/src/SMAPI.Internal.Patching/HarmonyPatcher.cs +++ b/src/SMAPI.Internal.Patching/HarmonyPatcher.cs @@ -15,7 +15,7 @@ namespace StardewModdingAPI.Internal.Patching /// <param name="patchers">The patchers to apply.</param> public static Harmony Apply(string id, IMonitor monitor, params IPatcher[] patchers) { - Harmony harmony = new Harmony(id); + Harmony harmony = new(id); foreach (IPatcher patcher in patchers) { diff --git a/src/SMAPI.Internal.Patching/PatchHelper.cs b/src/SMAPI.Internal.Patching/PatchHelper.cs index fc79ddf2..c9758616 100644 --- a/src/SMAPI.Internal.Patching/PatchHelper.cs +++ b/src/SMAPI.Internal.Patching/PatchHelper.cs @@ -43,7 +43,7 @@ namespace StardewModdingAPI.Internal.Patching /// <param name="generics">The method generic types, or <c>null</c> if it's not generic.</param> public static string GetMethodString(Type type, string name, Type[] parameters = null, Type[] generics = null) { - StringBuilder str = new StringBuilder(); + StringBuilder str = new(); // type str.Append(type.FullName); diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Item.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Item.cs index 1b6317c1..e8da92fa 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Item.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Item.cs @@ -7,27 +7,27 @@ namespace StardewValley public class Item { /// <summary>A net int field with an equivalent non-net <c>Category</c> property.</summary> - public readonly NetInt category = new NetInt { Value = 42 }; + public readonly NetInt category = new() { Value = 42 }; /// <summary>A generic net int field with no equivalent non-net property.</summary> - public readonly NetInt netIntField = new NetInt { Value = 42 }; + public readonly NetInt netIntField = new() { Value = 42 }; /// <summary>A generic net ref field with no equivalent non-net property.</summary> - public readonly NetRef<object> netRefField = new NetRef<object>(); + public readonly NetRef<object> netRefField = new(); /// <summary>A generic net int property with no equivalent non-net property.</summary> - public NetInt netIntProperty = new NetInt { Value = 42 }; + public NetInt netIntProperty = new() { Value = 42 }; /// <summary>A generic net ref property with no equivalent non-net property.</summary> - public NetRef<object> netRefProperty { get; } = new NetRef<object>(); + public NetRef<object> netRefProperty { get; } = new(); /// <summary>A sample net list.</summary> - public readonly NetList<int> netList = new NetList<int>(); + public readonly NetList<int> netList = new(); /// <summary>A sample net object list.</summary> - public readonly NetObjectList<int> netObjectList = new NetObjectList<int>(); + public readonly NetObjectList<int> netObjectList = new(); /// <summary>A sample net collection.</summary> - public readonly NetCollection<int> netCollection = new NetCollection<int>(); + public readonly NetCollection<int> netCollection = new(); } } diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Object.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Object.cs index 3dd66a6d..151010a7 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Object.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/Mock/StardewValley/Object.cs @@ -7,6 +7,6 @@ namespace StardewValley public class Object : Item { /// <summary>A net int field with an equivalent non-net property.</summary> - public NetInt type = new NetInt { Value = 42 }; + public NetInt type = new() { Value = 42 }; } } diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs index 89bd1be5..f11a59d3 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/NetFieldAnalyzerTests.cs @@ -93,7 +93,7 @@ namespace SMAPI.ModBuildConfig.Analyzer.Tests { // arrange string code = NetFieldAnalyzerTests.SampleProgram.Replace("{{test-code}}", codeText); - DiagnosticResult expected = new DiagnosticResult + DiagnosticResult expected = new() { Id = "AvoidImplicitNetFieldCast", Message = $"This implicitly converts '{expression}' from {fromType} to {toType}, but {fromType} has unintuitive implicit conversion rules. Consider comparing against the actual value instead to avoid bugs. See https://smapi.io/package/avoid-implicit-net-field-cast for details.", @@ -135,7 +135,7 @@ namespace SMAPI.ModBuildConfig.Analyzer.Tests { // arrange string code = NetFieldAnalyzerTests.SampleProgram.Replace("{{test-code}}", codeText); - DiagnosticResult expected = new DiagnosticResult + DiagnosticResult expected = new() { Id = "AvoidNetField", Message = $"'{expression}' is a {netType} field; consider using the {suggestedProperty} property instead. See https://smapi.io/package/avoid-net-field for details.", diff --git a/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs b/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs index 12641e1a..76607b8e 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer.Tests/ObsoleteFieldAnalyzerTests.cs @@ -64,7 +64,7 @@ namespace SMAPI.ModBuildConfig.Analyzer.Tests { // arrange string code = ObsoleteFieldAnalyzerTests.SampleProgram.Replace("{{test-code}}", codeText); - DiagnosticResult expected = new DiagnosticResult + DiagnosticResult expected = new() { Id = "AvoidObsoleteField", Message = $"The '{oldName}' field is obsolete and should be replaced with '{newName}'. See https://smapi.io/package/avoid-obsolete-field for details.", diff --git a/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs b/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs index e03c72de..8478dc54 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer/NetFieldAnalyzer.cs @@ -132,7 +132,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer }; /// <summary>The diagnostic info for an implicit net field cast.</summary> - private readonly DiagnosticDescriptor AvoidImplicitNetFieldCastRule = new DiagnosticDescriptor( + private readonly DiagnosticDescriptor AvoidImplicitNetFieldCastRule = new( id: "AvoidImplicitNetFieldCast", title: "Netcode types shouldn't be implicitly converted", messageFormat: "This implicitly converts '{0}' from {1} to {2}, but {1} has unintuitive implicit conversion rules. Consider comparing against the actual value instead to avoid bugs. See https://smapi.io/package/avoid-implicit-net-field-cast for details.", @@ -143,7 +143,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer ); /// <summary>The diagnostic info for an avoidable net field access.</summary> - private readonly DiagnosticDescriptor AvoidNetFieldRule = new DiagnosticDescriptor( + private readonly DiagnosticDescriptor AvoidNetFieldRule = new( id: "AvoidNetField", title: "Avoid Netcode types when possible", messageFormat: "'{0}' is a {1} field; consider using the {2} property instead. See https://smapi.io/package/avoid-net-field for details.", diff --git a/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs b/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs index 722d5227..3184147a 100644 --- a/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs +++ b/src/SMAPI.ModBuildConfig.Analyzer/ObsoleteFieldAnalyzer.cs @@ -24,7 +24,7 @@ namespace StardewModdingAPI.ModBuildConfig.Analyzer /// <summary>Describes the diagnostic rule covered by the analyzer.</summary> private readonly IDictionary<string, DiagnosticDescriptor> Rules = new Dictionary<string, DiagnosticDescriptor> { - ["AvoidObsoleteField"] = new DiagnosticDescriptor( + ["AvoidObsoleteField"] = new( id: "AvoidObsoleteField", title: "Reference to obsolete field", messageFormat: "The '{0}' field is obsolete and should be replaced with '{1}'. See https://smapi.io/package/avoid-obsolete-field for details.", diff --git a/src/SMAPI.ModBuildConfig/DeployModTask.cs b/src/SMAPI.ModBuildConfig/DeployModTask.cs index 140933bd..c7026ee1 100644 --- a/src/SMAPI.ModBuildConfig/DeployModTask.cs +++ b/src/SMAPI.ModBuildConfig/DeployModTask.cs @@ -88,7 +88,7 @@ namespace StardewModdingAPI.ModBuildConfig Regex[] ignoreFilePatterns = this.GetCustomIgnorePatterns().ToArray(); // get mod info - ModFileManager package = new ModFileManager(this.ProjectDir, this.TargetDir, ignoreFilePaths, ignoreFilePatterns, bundleAssemblyTypes, this.ModDllName, validateRequiredModFiles: this.EnableModDeploy || this.EnableModZip); + ModFileManager package = new(this.ProjectDir, this.TargetDir, ignoreFilePaths, ignoreFilePatterns, bundleAssemblyTypes, this.ModDllName, validateRequiredModFiles: this.EnableModDeploy || this.EnableModZip); // deploy mod files if (this.EnableModDeploy) @@ -246,7 +246,7 @@ namespace StardewModdingAPI.ModBuildConfig // create zip file Directory.CreateDirectory(Path.GetDirectoryName(zipPath)!); using Stream zipStream = new FileStream(zipPath, FileMode.Create, FileAccess.Write); - using ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create); + using ZipArchive archive = new(zipStream, ZipArchiveMode.Create); foreach (var fileEntry in files) { diff --git a/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs b/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs index ad4ffdf9..80955f67 100644 --- a/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs +++ b/src/SMAPI.ModBuildConfig/Framework/ModFileManager.cs @@ -136,7 +136,7 @@ namespace StardewModdingAPI.ModBuildConfig.Framework // project manifest bool hasProjectManifest = false; { - FileInfo manifest = new FileInfo(Path.Combine(projectDir, this.ManifestFileName)); + FileInfo manifest = new(Path.Combine(projectDir, this.ManifestFileName)); if (manifest.Exists) { yield return Tuple.Create(this.ManifestFileName, manifest); @@ -146,7 +146,7 @@ namespace StardewModdingAPI.ModBuildConfig.Framework // project i18n files bool hasProjectTranslations = false; - DirectoryInfo translationsFolder = new DirectoryInfo(Path.Combine(projectDir, "i18n")); + DirectoryInfo translationsFolder = new(Path.Combine(projectDir, "i18n")); if (translationsFolder.Exists) { foreach (FileInfo file in translationsFolder.EnumerateFiles()) @@ -156,7 +156,7 @@ namespace StardewModdingAPI.ModBuildConfig.Framework // project assets folder bool hasAssetsFolder = false; - DirectoryInfo assetsFolder = new DirectoryInfo(Path.Combine(projectDir, "assets")); + DirectoryInfo assetsFolder = new(Path.Combine(projectDir, "assets")); if (assetsFolder.Exists) { foreach (FileInfo file in assetsFolder.EnumerateFiles("*", SearchOption.AllDirectories)) @@ -168,7 +168,7 @@ namespace StardewModdingAPI.ModBuildConfig.Framework } // build output - DirectoryInfo buildFolder = new DirectoryInfo(targetDir); + DirectoryInfo buildFolder = new(targetDir); foreach (FileInfo file in buildFolder.EnumerateFiles("*", SearchOption.AllDirectories)) { // get path info diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs index 0e8f7517..fae31c23 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/AddCommand.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player ** Fields *********/ /// <summary>Provides methods for searching and constructing items.</summary> - private readonly ItemRepository Items = new ItemRepository(); + private readonly ItemRepository Items = new(); /// <summary>The type names recognized by this command.</summary> private readonly string[] ValidTypes = Enum.GetNames(typeof(ItemType)).Concat(new[] { "Name" }).ToArray(); diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemTypesCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemTypesCommand.cs index 1f12e5f9..af362bcd 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemTypesCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemTypesCommand.cs @@ -10,7 +10,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player ** Fields *********/ /// <summary>Provides methods for searching and constructing items.</summary> - private readonly ItemRepository Items = new ItemRepository(); + private readonly ItemRepository Items = new(); /********* diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs index 67569298..46fc1d9d 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/Commands/Player/ListItemsCommand.cs @@ -12,7 +12,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework.Commands.Player ** Fields *********/ /// <summary>Provides methods for searching and constructing items.</summary> - private readonly ItemRepository Items = new ItemRepository(); + private readonly ItemRepository Items = new(); /********* diff --git a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs index 8704a403..9b48fa99 100644 --- a/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs +++ b/src/SMAPI.Mods.ConsoleCommands/Framework/ItemRepository.cs @@ -285,7 +285,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands.Framework case SObject.flowersCategory: yield return this.TryCreate(ItemType.Object, this.CustomIDOffset * 5 + id, _ => { - SObject honey = new SObject(Vector2.Zero, 340, $"{item.Name} Honey", false, true, false, false) + SObject honey = new(Vector2.Zero, 340, $"{item.Name} Honey", false, true, false, false) { Name = $"{item.Name} Honey", preservedParentSheetIndex = { id } diff --git a/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs b/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs index 91437fd3..5e594984 100644 --- a/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs +++ b/src/SMAPI.Mods.ConsoleCommands/ModEntry.cs @@ -71,7 +71,7 @@ namespace StardewModdingAPI.Mods.ConsoleCommands /// <param name="args">The command arguments.</param> private void HandleCommand(IConsoleCommand command, string commandName, string[] args) { - ArgumentParser argParser = new ArgumentParser(commandName, args, this.Monitor); + ArgumentParser argParser = new(commandName, args, this.Monitor); command.Handle(this.Monitor, commandName, argParser); } diff --git a/src/SMAPI.Mods.ErrorHandler/Patches/SaveGamePatcher.cs b/src/SMAPI.Mods.ErrorHandler/Patches/SaveGamePatcher.cs index 0a7ed212..5f6dbcb3 100644 --- a/src/SMAPI.Mods.ErrorHandler/Patches/SaveGamePatcher.cs +++ b/src/SMAPI.Mods.ErrorHandler/Patches/SaveGamePatcher.cs @@ -121,7 +121,7 @@ namespace StardewModdingAPI.Mods.ErrorHandler.Patches { try { - BluePrint _ = new BluePrint(building.buildingType.Value); + BluePrint _ = new(building.buildingType.Value); } catch (ContentLoadException) { diff --git a/src/SMAPI.Mods.SaveBackup/ModEntry.cs b/src/SMAPI.Mods.SaveBackup/ModEntry.cs index b89bb9c3..f6925707 100644 --- a/src/SMAPI.Mods.SaveBackup/ModEntry.cs +++ b/src/SMAPI.Mods.SaveBackup/ModEntry.cs @@ -38,7 +38,7 @@ namespace StardewModdingAPI.Mods.SaveBackup try { // init backup folder - DirectoryInfo backupFolder = new DirectoryInfo(this.BackupFolder); + DirectoryInfo backupFolder = new(this.BackupFolder); backupFolder.Create(); // back up & prune saves @@ -63,8 +63,8 @@ namespace StardewModdingAPI.Mods.SaveBackup try { // get target path - FileInfo targetFile = new FileInfo(Path.Combine(backupFolder.FullName, this.FileName)); - DirectoryInfo fallbackDir = new DirectoryInfo(Path.Combine(backupFolder.FullName, this.BackupLabel)); + FileInfo targetFile = new(Path.Combine(backupFolder.FullName, this.FileName)); + DirectoryInfo fallbackDir = new(Path.Combine(backupFolder.FullName, this.BackupLabel)); if (targetFile.Exists || fallbackDir.Exists) { this.Monitor.Log("Already backed up today."); @@ -72,7 +72,7 @@ namespace StardewModdingAPI.Mods.SaveBackup } // copy saves to fallback directory (ignore non-save files/folders) - DirectoryInfo savesDir = new DirectoryInfo(Constants.SavesPath); + DirectoryInfo savesDir = new(Constants.SavesPath); if (!this.RecursiveCopy(savesDir, fallbackDir, entry => this.MatchSaveFolders(savesDir, entry), copyRoot: false)) { this.Monitor.Log("No saves found."); @@ -190,8 +190,8 @@ namespace StardewModdingAPI.Mods.SaveBackup /// <param name="destination">The destination file to create.</param> private void CompressUsingMacProcess(string sourcePath, FileInfo destination) { - DirectoryInfo saveFolder = new DirectoryInfo(sourcePath); - ProcessStartInfo startInfo = new ProcessStartInfo + DirectoryInfo saveFolder = new(sourcePath); + ProcessStartInfo startInfo = new() { FileName = "zip", Arguments = $"-rq \"{destination.FullName}\" \"{saveFolder.Name}\" -x \"*.DS_Store\" -x \"__MACOSX\"", diff --git a/src/SMAPI.Tests/Core/TranslationTests.cs b/src/SMAPI.Tests/Core/TranslationTests.cs index 457f9fad..58bc59b1 100644 --- a/src/SMAPI.Tests/Core/TranslationTests.cs +++ b/src/SMAPI.Tests/Core/TranslationTests.cs @@ -116,7 +116,7 @@ namespace SMAPI.Tests.Core public void Translation_ToString([ValueSource(nameof(TranslationTests.Samples))] string text) { // act - Translation translation = new Translation("pt-BR", "key", text); + Translation translation = new("pt-BR", "key", text); // assert if (translation.HasValue()) @@ -129,7 +129,7 @@ namespace SMAPI.Tests.Core public void Translation_ImplicitStringConversion([ValueSource(nameof(TranslationTests.Samples))] string text) { // act - Translation translation = new Translation("pt-BR", "key", text); + Translation translation = new("pt-BR", "key", text); // assert if (translation.HasValue()) @@ -182,7 +182,7 @@ namespace SMAPI.Tests.Core string expected = $"{start} tokens are properly replaced (including {middle} {middle}) {end}"; // act - Translation translation = new Translation("pt-BR", "key", input); + Translation translation = new("pt-BR", "key", input); switch (structure) { case "anonymous object": diff --git a/src/SMAPI.Tests/Sample.cs b/src/SMAPI.Tests/Sample.cs index f4f0d88e..9587a100 100644 --- a/src/SMAPI.Tests/Sample.cs +++ b/src/SMAPI.Tests/Sample.cs @@ -9,7 +9,7 @@ namespace SMAPI.Tests ** Fields *********/ /// <summary>A random number generator.</summary> - private static readonly Random Random = new Random(); + private static readonly Random Random = new(); /********* diff --git a/src/SMAPI.Tests/Utilities/PathUtilitiesTests.cs b/src/SMAPI.Tests/Utilities/PathUtilitiesTests.cs index ab4c2618..94819c2e 100644 --- a/src/SMAPI.Tests/Utilities/PathUtilitiesTests.cs +++ b/src/SMAPI.Tests/Utilities/PathUtilitiesTests.cs @@ -14,7 +14,7 @@ namespace SMAPI.Tests.Utilities /// <summary>Sample paths used in unit tests.</summary> public static readonly SamplePath[] SamplePaths = { // Windows absolute path - new SamplePath + new() { OriginalPath = @"C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley", @@ -26,7 +26,7 @@ namespace SMAPI.Tests.Utilities }, // Windows absolute path (with trailing slash) - new SamplePath + new() { OriginalPath = @"C:\Program Files (x86)\Steam\steamapps\common\Stardew Valley\", @@ -38,7 +38,7 @@ namespace SMAPI.Tests.Utilities }, // Windows relative path - new SamplePath + new() { OriginalPath = @"Content\Characters\Dialogue\Abigail", @@ -50,7 +50,7 @@ namespace SMAPI.Tests.Utilities }, // Windows relative path (with directory climbing) - new SamplePath + new() { OriginalPath = @"..\..\Content", @@ -62,7 +62,7 @@ namespace SMAPI.Tests.Utilities }, // Windows UNC path - new SamplePath + new() { OriginalPath = @"\\unc\path", @@ -74,7 +74,7 @@ namespace SMAPI.Tests.Utilities }, // Linux absolute path - new SamplePath + new() { OriginalPath = @"/home/.steam/steam/steamapps/common/Stardew Valley", @@ -86,7 +86,7 @@ namespace SMAPI.Tests.Utilities }, // Linux absolute path (with trailing slash) - new SamplePath + new() { OriginalPath = @"/home/.steam/steam/steamapps/common/Stardew Valley/", @@ -98,7 +98,7 @@ namespace SMAPI.Tests.Utilities }, // Linux absolute path (with ~) - new SamplePath + new() { OriginalPath = @"~/.steam/steam/steamapps/common/Stardew Valley", @@ -110,7 +110,7 @@ namespace SMAPI.Tests.Utilities }, // Linux relative path - new SamplePath + new() { OriginalPath = @"Content/Characters/Dialogue/Abigail", @@ -122,7 +122,7 @@ namespace SMAPI.Tests.Utilities }, // Linux relative path (with directory climbing) - new SamplePath + new() { OriginalPath = @"../../Content", @@ -134,7 +134,7 @@ namespace SMAPI.Tests.Utilities }, // Mixed directory separators - new SamplePath + new() { OriginalPath = @"C:\some/mixed\path/separators", diff --git a/src/SMAPI.Tests/Utilities/SDateTests.cs b/src/SMAPI.Tests/Utilities/SDateTests.cs index 374f4921..886f25cd 100644 --- a/src/SMAPI.Tests/Utilities/SDateTests.cs +++ b/src/SMAPI.Tests/Utilities/SDateTests.cs @@ -61,7 +61,7 @@ namespace SMAPI.Tests.Utilities public void Constructor_SetsExpectedValues([ValueSource(nameof(SDateTests.SampleSeasonValues))] string season, [ValueSource(nameof(SDateTests.ValidDays))] int day, [Values(1, 2, 100)] int year) { // act - SDate date = new SDate(day, season, year); + SDate date = new(day, season, year); // assert Assert.AreEqual(day, date.Day); @@ -254,7 +254,7 @@ namespace SMAPI.Tests.Utilities { foreach (int day in SDateTests.ValidDays) { - SDate date = new SDate(day, season, year); + SDate date = new(day, season, year); int hash = date.GetHashCode(); if (hashes.TryGetValue(hash, out SDate otherDate)) Assert.Fail($"Received identical hash code {hash} for dates {otherDate} and {date}."); diff --git a/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs b/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs index ac4ef39b..c8270373 100644 --- a/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs +++ b/src/SMAPI.Tests/Utilities/SemanticVersionTests.cs @@ -395,7 +395,7 @@ namespace SMAPI.Tests.Utilities public void GameVersion(string versionStr) { // act - GameVersion version = new GameVersion(versionStr); + GameVersion version = new(versionStr); // assert Assert.AreEqual(versionStr, version.ToString(), "The game version did not round-trip to the same value."); diff --git a/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs index c2d906a0..f7d26d21 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/WebApi/WebApiClient.cs @@ -62,9 +62,9 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.WebApi private TResult Post<TBody, TResult>(string url, TBody content) { // note: avoid HttpClient for macOS compatibility - using WebClient client = new WebClient(); + using WebClient client = new(); - Uri fullUrl = new Uri(this.BaseUrl, url); + Uri fullUrl = new(this.BaseUrl, url); string data = JsonConvert.SerializeObject(content); client.Headers["Content-Type"] = "application/json"; diff --git a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs index 0f5a0ec3..abbcdc81 100644 --- a/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs +++ b/src/SMAPI.Toolkit/Framework/Clients/Wiki/WikiClient.cs @@ -127,7 +127,7 @@ namespace StardewModdingAPI.Toolkit.Framework.Clients.Wiki string pullRequestUrl = this.GetAttribute(node, "data-pr"); // parse stable compatibility - WikiCompatibilityInfo compatibility = new WikiCompatibilityInfo + WikiCompatibilityInfo compatibility = new() { Status = this.GetAttributeAsEnum<WikiCompatibilityStatus>(node, "data-status") ?? WikiCompatibilityStatus.Ok, BrokeIn = this.GetAttribute(node, "data-broke-in"), diff --git a/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs b/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs index 8d4198de..768beba1 100644 --- a/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs +++ b/src/SMAPI.Toolkit/Framework/GameScanning/GameScanner.cs @@ -45,7 +45,7 @@ namespace StardewModdingAPI.Toolkit.Framework.GameScanning // yield valid folders foreach (string path in paths) { - DirectoryInfo folder = new DirectoryInfo(path); + DirectoryInfo folder = new(path); if (this.LooksLikeGameFolder(folder)) yield return folder; } @@ -191,7 +191,7 @@ namespace StardewModdingAPI.Toolkit.Framework.GameScanning yield break; // get targets file - FileInfo file = new FileInfo(Path.Combine(homePath, "stardewvalley.targets")); + FileInfo file = new(Path.Combine(homePath, "stardewvalley.targets")); if (!file.Exists) yield break; diff --git a/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs b/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs index 8b6eb5fb..c0332331 100644 --- a/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs +++ b/src/SMAPI.Toolkit/Framework/LowLevelEnvironmentUtility.cs @@ -98,7 +98,7 @@ namespace StardewModdingAPI.Toolkit.Framework /// </remarks> private static bool IsRunningAndroid() { - using Process process = new Process + using Process process = new() { StartInfo = { diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs index 5dd32acf..7e07ffde 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs @@ -82,7 +82,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /// <param name="manifest">The manifest to match.</param> public ModDataRecordVersionedFields GetVersionedFields(IManifest manifest) { - ModDataRecordVersionedFields parsed = new ModDataRecordVersionedFields { DisplayName = this.DisplayName, DataRecord = this }; + ModDataRecordVersionedFields parsed = new() { DisplayName = this.DisplayName, DataRecord = this }; foreach (ModDataField field in this.Fields.Where(field => field.IsMatch(manifest))) { switch (field.Key) diff --git a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs index e6105f9c..d21ccec0 100644 --- a/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs +++ b/src/SMAPI.Toolkit/Framework/ModScanning/ModScanner.cs @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning private readonly JsonHelper JsonHelper; /// <summary>A list of filesystem entry names to ignore when checking whether a folder should be treated as a mod.</summary> - private readonly HashSet<Regex> IgnoreFilesystemNames = new HashSet<Regex> + private readonly HashSet<Regex> IgnoreFilesystemNames = new() { new Regex(@"^__folder_managed_by_vortex$", RegexOptions.Compiled | RegexOptions.IgnoreCase), // Vortex mod manager new Regex(@"(?:^\._|^\.DS_Store$|^__MACOSX$|^mcs$)", RegexOptions.Compiled | RegexOptions.IgnoreCase), // macOS @@ -26,7 +26,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning }; /// <summary>A list of file extensions to ignore when searching for mod files.</summary> - private readonly HashSet<string> IgnoreFileExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) + private readonly HashSet<string> IgnoreFileExtensions = new(StringComparer.OrdinalIgnoreCase) { // text ".doc", @@ -60,7 +60,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning }; /// <summary>The extensions for packed content files.</summary> - private readonly HashSet<string> StrictXnbModExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) + private readonly HashSet<string> StrictXnbModExtensions = new(StringComparer.OrdinalIgnoreCase) { ".xgs", ".xnb", @@ -69,7 +69,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning }; /// <summary>The extensions for files which an XNB mod may contain, in addition to <see cref="StrictXnbModExtensions"/>.</summary> - private readonly HashSet<string> PotentialXnbModExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) + private readonly HashSet<string> PotentialXnbModExtensions = new(StringComparer.OrdinalIgnoreCase) { ".json", ".yaml" @@ -96,7 +96,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning /// <param name="rootPath">The root folder containing mods.</param> public IEnumerable<ModFolder> GetModFolders(string rootPath) { - DirectoryInfo root = new DirectoryInfo(rootPath); + DirectoryInfo root = new(rootPath); return this.GetModFolders(root, root); } @@ -260,7 +260,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModScanning while (true) { // check for manifest in current folder - FileInfo file = new FileInfo(Path.Combine(folder.FullName, "manifest.json")); + FileInfo file = new(Path.Combine(folder.FullName, "manifest.json")); if (file.Exists) return file; diff --git a/src/SMAPI.Toolkit/ModToolkit.cs b/src/SMAPI.Toolkit/ModToolkit.cs index 38a67ae5..80008df7 100644 --- a/src/SMAPI.Toolkit/ModToolkit.cs +++ b/src/SMAPI.Toolkit/ModToolkit.cs @@ -34,7 +34,7 @@ namespace StardewModdingAPI.Toolkit ** Accessors *********/ /// <summary>Encapsulates SMAPI's JSON parsing.</summary> - public JsonHelper JsonHelper { get; } = new JsonHelper(); + public JsonHelper JsonHelper { get; } = new(); /********* diff --git a/src/SMAPI.Toolkit/SemanticVersionComparer.cs b/src/SMAPI.Toolkit/SemanticVersionComparer.cs index 9f6b57a2..8eba2c9f 100644 --- a/src/SMAPI.Toolkit/SemanticVersionComparer.cs +++ b/src/SMAPI.Toolkit/SemanticVersionComparer.cs @@ -9,7 +9,7 @@ namespace StardewModdingAPI.Toolkit ** Accessors *********/ /// <summary>A singleton instance of the comparer.</summary> - public static SemanticVersionComparer Instance { get; } = new SemanticVersionComparer(); + public static SemanticVersionComparer Instance { get; } = new(); /********* diff --git a/src/SMAPI.Toolkit/Serialization/JsonHelper.cs b/src/SMAPI.Toolkit/Serialization/JsonHelper.cs index 00db9903..5c465f3c 100644 --- a/src/SMAPI.Toolkit/Serialization/JsonHelper.cs +++ b/src/SMAPI.Toolkit/Serialization/JsonHelper.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI.Toolkit.Serialization ** Accessors *********/ /// <summary>The JSON settings to use when serializing and deserializing files.</summary> - public JsonSerializerSettings JsonSettings { get; } = new JsonSerializerSettings + public JsonSerializerSettings JsonSettings { get; } = new() { Formatting = Formatting.Indented, ObjectCreationHandling = ObjectCreationHandling.Replace, // avoid issue where default ICollection<T> values are duplicated each time the config is loaded diff --git a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs index 2e9e5eac..85e12bfa 100644 --- a/src/SMAPI.Toolkit/Utilities/PathUtilities.cs +++ b/src/SMAPI.Toolkit/Utilities/PathUtilities.cs @@ -100,8 +100,8 @@ namespace StardewModdingAPI.Toolkit.Utilities // though, this is only for compatibility with the mod build package. // convert to URIs - Uri from = new Uri(sourceDir.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); - Uri to = new Uri(targetPath.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); + Uri from = new(sourceDir.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); + Uri to = new(targetPath.TrimEnd(PathUtilities.PossiblePathSeparators) + "/"); if (from.Scheme != to.Scheme) throw new InvalidOperationException($"Can't get path for '{targetPath}' relative to '{sourceDir}'."); diff --git a/src/SMAPI.Web/Controllers/IndexController.cs b/src/SMAPI.Web/Controllers/IndexController.cs index 5097997c..69b54f47 100644 --- a/src/SMAPI.Web/Controllers/IndexController.cs +++ b/src/SMAPI.Web/Controllers/IndexController.cs @@ -94,7 +94,7 @@ namespace StardewModdingAPI.Web.Controllers // strip 'noinclude' blocks from release description if (release != null) { - HtmlDocument doc = new HtmlDocument(); + HtmlDocument doc = new(); doc.LoadHtml(release.Body); foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//*[@class='noinclude']")?.ToArray() ?? Array.Empty<HtmlNode>()) node.Remove(); diff --git a/src/SMAPI.Web/Controllers/JsonValidatorController.cs b/src/SMAPI.Web/Controllers/JsonValidatorController.cs index e06c1236..bcd4097a 100644 --- a/src/SMAPI.Web/Controllers/JsonValidatorController.cs +++ b/src/SMAPI.Web/Controllers/JsonValidatorController.cs @@ -197,7 +197,7 @@ namespace StardewModdingAPI.Web.Controllers return null; // get matching file - DirectoryInfo schemaDir = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "schemas")); + DirectoryInfo schemaDir = new(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "schemas")); foreach (FileInfo file in schemaDir.EnumerateFiles("*.json")) { if (file.Name.Equals($"{id}.json")) diff --git a/src/SMAPI.Web/Controllers/ModsApiController.cs b/src/SMAPI.Web/Controllers/ModsApiController.cs index dfe2504b..5329df99 100644 --- a/src/SMAPI.Web/Controllers/ModsApiController.cs +++ b/src/SMAPI.Web/Controllers/ModsApiController.cs @@ -135,7 +135,7 @@ namespace StardewModdingAPI.Web.Controllers bool isSmapiBeta = apiVersion.IsPrerelease() && apiVersion.PrereleaseTag.StartsWith("beta"); // get latest versions - ModEntryModel result = new ModEntryModel { ID = search.ID }; + ModEntryModel result = new() { ID = search.ID }; IList<string> errors = new List<string>(); ModEntryVersionModel main = null; ModEntryVersionModel optional = null; diff --git a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs index b8b05878..9689807c 100644 --- a/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Chucklefish/ChucklefishClient.cs @@ -90,7 +90,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Chucklefish /// <param name="id">The mod ID.</param> private string GetModUrl(uint id) { - UriBuilder builder = new UriBuilder(this.Client.BaseClient.BaseAddress); + UriBuilder builder = new(this.Client.BaseClient.BaseAddress); builder.Path += string.Format(this.ModPageUrlFormat, id); return builder.Uri.ToString(); } diff --git a/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs index d8008721..50a3336d 100644 --- a/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs +++ b/src/SMAPI.Web/Framework/Clients/CurseForge/CurseForgeClient.cs @@ -17,7 +17,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.CurseForge private readonly IClient Client; /// <summary>A regex pattern which matches a version number in a CurseForge mod file name.</summary> - private readonly Regex VersionInNamePattern = new Regex(@"^(?:.+? | *)v?(\d+\.\d+(?:\.\d+)?(?:-.+?)?) *(?:\.(?:zip|rar|7z))?$", RegexOptions.Compiled); + private readonly Regex VersionInNamePattern = new(@"^(?:.+? | *)v?(\d+\.\d+(?:\.\d+)?(?:-.+?)?) *(?:\.(?:zip|rar|7z))?$", RegexOptions.Compiled); /********* diff --git a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs index 4ba94f81..571f06bc 100644 --- a/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs +++ b/src/SMAPI.Web/Framework/Clients/Nexus/NexusClient.cs @@ -195,7 +195,7 @@ namespace StardewModdingAPI.Web.Framework.Clients.Nexus /// <param name="id">The mod ID.</param> private string GetModUrl(uint id) { - UriBuilder builder = new UriBuilder(this.WebClient.BaseClient.BaseAddress); + UriBuilder builder = new(this.WebClient.BaseClient.BaseAddress); builder.Path += string.Format(this.WebModUrlFormat, id); return builder.Uri.ToString(); } diff --git a/src/SMAPI.Web/Framework/Compression/GzipHelper.cs b/src/SMAPI.Web/Framework/Compression/GzipHelper.cs index 676d660d..93cde9d3 100644 --- a/src/SMAPI.Web/Framework/Compression/GzipHelper.cs +++ b/src/SMAPI.Web/Framework/Compression/GzipHelper.cs @@ -29,9 +29,9 @@ namespace StardewModdingAPI.Web.Framework.Compression // compressed byte[] compressedData; - using (MemoryStream stream = new MemoryStream()) + using (MemoryStream stream = new()) { - using (GZipStream zipStream = new GZipStream(stream, CompressionLevel.Optimal, leaveOpen: true)) + using (GZipStream zipStream = new(stream, CompressionLevel.Optimal, leaveOpen: true)) zipStream.Write(buffer, 0, buffer.Length); stream.Position = 0; @@ -69,7 +69,7 @@ namespace StardewModdingAPI.Web.Framework.Compression return rawText; // decompress - using MemoryStream memoryStream = new MemoryStream(); + using MemoryStream memoryStream = new(); { // read length prefix int dataLength = BitConverter.ToInt32(zipBuffer, 0); @@ -78,7 +78,7 @@ namespace StardewModdingAPI.Web.Framework.Compression // read data byte[] buffer = new byte[dataLength]; memoryStream.Position = 0; - using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress)) + using (GZipStream gZipStream = new(memoryStream, CompressionMode.Decompress)) gZipStream.Read(buffer, 0, buffer.Length); // return original string diff --git a/src/SMAPI.Web/Framework/Extensions.cs b/src/SMAPI.Web/Framework/Extensions.cs index 5305b142..2e767b3d 100644 --- a/src/SMAPI.Web/Framework/Extensions.cs +++ b/src/SMAPI.Web/Framework/Extensions.cs @@ -29,7 +29,7 @@ namespace StardewModdingAPI.Web.Framework public static string PlainAction(this IUrlHelper helper, [AspMvcAction] string action, [AspMvcController] string controller, object values = null, bool absoluteUrl = false) { // get route values - RouteValueDictionary valuesDict = new RouteValueDictionary(values); + RouteValueDictionary valuesDict = new(values); foreach (var value in helper.ActionContext.RouteData.Values) { if (!valuesDict.ContainsKey(value.Key)) @@ -45,7 +45,7 @@ namespace StardewModdingAPI.Web.Framework if (absoluteUrl) { HttpRequest request = helper.ActionContext.HttpContext.Request; - Uri baseUri = new Uri($"{request.Scheme}://{request.Host}"); + Uri baseUri = new($"{request.Scheme}://{request.Host}"); url = new Uri(baseUri, url).ToString(); } diff --git a/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs b/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs index 385c0c91..3c1405eb 100644 --- a/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs +++ b/src/SMAPI.Web/Framework/JobDashboardAuthorizationFilter.cs @@ -9,7 +9,7 @@ namespace StardewModdingAPI.Web.Framework ** Fields *********/ /// <summary>An authorization filter that allows local requests.</summary> - private static readonly LocalRequestsOnlyAuthorizationFilter LocalRequestsOnlyFilter = new LocalRequestsOnlyAuthorizationFilter(); + private static readonly LocalRequestsOnlyAuthorizationFilter LocalRequestsOnlyFilter = new(); /********* diff --git a/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs b/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs index 992876ef..9da27d61 100644 --- a/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs +++ b/src/SMAPI.Web/Framework/LogParsing/LogMessageBuilder.cs @@ -23,7 +23,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing public string Mod { get; set; } /// <summary>The text for the next log message.</summary> - private readonly StringBuilder Text = new StringBuilder(); + private readonly StringBuilder Text = new(); /********* diff --git a/src/SMAPI.Web/Framework/LogParsing/LogParser.cs b/src/SMAPI.Web/Framework/LogParsing/LogParser.cs index 887d0105..6a3ea222 100644 --- a/src/SMAPI.Web/Framework/LogParsing/LogParser.cs +++ b/src/SMAPI.Web/Framework/LogParsing/LogParser.cs @@ -14,38 +14,38 @@ namespace StardewModdingAPI.Web.Framework.LogParsing ** Fields *********/ /// <summary>A regex pattern matching the start of a SMAPI message.</summary> - private readonly Regex MessageHeaderPattern = new Regex(@"^\[(?<time>\d\d[:\.]\d\d[:\.]\d\d) (?<level>[a-z]+)(?: +screen_(?<screen>\d+))? +(?<modName>[^\]]+)\] ", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex MessageHeaderPattern = new(@"^\[(?<time>\d\d[:\.]\d\d[:\.]\d\d) (?<level>[a-z]+)(?: +screen_(?<screen>\d+))? +(?<modName>[^\]]+)\] ", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's initial platform info message.</summary> - private readonly Regex InfoLinePattern = new Regex(@"^SMAPI (?<apiVersion>.+) with Stardew Valley (?<gameVersion>.+) on (?<os>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex InfoLinePattern = new(@"^SMAPI (?<apiVersion>.+) with Stardew Valley (?<gameVersion>.+) on (?<os>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's mod folder path line.</summary> - private readonly Regex ModPathPattern = new Regex(@"^Mods go here: (?<path>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModPathPattern = new(@"^Mods go here: (?<path>.+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's log timestamp line.</summary> - private readonly Regex LogStartedAtPattern = new Regex(@"^Log started at (?<timestamp>.+) UTC", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex LogStartedAtPattern = new(@"^Log started at (?<timestamp>.+) UTC", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching the start of SMAPI's mod list.</summary> - private readonly Regex ModListStartPattern = new Regex(@"^Loaded \d+ mods:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModListStartPattern = new(@"^Loaded \d+ mods:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching an entry in SMAPI's mod list.</summary> /// <remarks>The author name and description are optional.</remarks> - private readonly Regex ModListEntryPattern = new Regex(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))?(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModListEntryPattern = new(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))?(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching the start of SMAPI's content pack list.</summary> - private readonly Regex ContentPackListStartPattern = new Regex(@"^Loaded \d+ content packs:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ContentPackListStartPattern = new(@"^Loaded \d+ content packs:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching an entry in SMAPI's content pack list.</summary> - private readonly Regex ContentPackListEntryPattern = new Regex(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))? \| for (?<for>[^\|]+)(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ContentPackListEntryPattern = new(@"^ (?<name>.+?) (?<version>[^\s]+)(?: by (?<author>[^\|]+))? \| for (?<for>[^\|]+)(?: \| (?<description>.+))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching the start of SMAPI's mod update list.</summary> - private readonly Regex ModUpdateListStartPattern = new Regex(@"^You can update \d+ mods?:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModUpdateListStartPattern = new(@"^You can update \d+ mods?:$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching an entry in SMAPI's mod update list.</summary> - private readonly Regex ModUpdateListEntryPattern = new Regex(@"^ (?<name>.+) (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex ModUpdateListEntryPattern = new(@"^ (?<name>.+) (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /// <summary>A regex pattern matching SMAPI's update line.</summary> - private readonly Regex SmapiUpdatePattern = new Regex(@"^You can update SMAPI to (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex SmapiUpdatePattern = new(@"^You can update SMAPI to (?<version>[^\s]+): (?<link>.+)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); /********* @@ -69,7 +69,7 @@ namespace StardewModdingAPI.Web.Framework.LogParsing } // init log - ParsedLog log = new ParsedLog + ParsedLog log = new() { IsValid = true, RawText = logText, @@ -77,8 +77,8 @@ namespace StardewModdingAPI.Web.Framework.LogParsing }; // parse log messages - LogModInfo smapiMod = new LogModInfo { Name = "SMAPI", Author = "Pathoschild", Description = "", Loaded = true }; - LogModInfo gameMod = new LogModInfo { Name = "game", Author = "", Description = "", Loaded = true }; + LogModInfo smapiMod = new() { Name = "SMAPI", Author = "Pathoschild", Description = "", Loaded = true }; + LogModInfo gameMod = new() { Name = "game", Author = "", Description = "", Loaded = true }; IDictionary<string, List<LogModInfo>> mods = new Dictionary<string, List<LogModInfo>>(); bool inModList = false; bool inContentPackList = false; @@ -288,8 +288,8 @@ namespace StardewModdingAPI.Web.Framework.LogParsing /// <exception cref="LogParseException">The log text can't be parsed successfully.</exception> private IEnumerable<LogMessage> GetMessages(string logText) { - LogMessageBuilder builder = new LogMessageBuilder(); - using StringReader reader = new StringReader(logText); + LogMessageBuilder builder = new(); + using StringReader reader = new(logText); while (true) { // read line diff --git a/src/SMAPI.Web/Framework/Storage/StorageProvider.cs b/src/SMAPI.Web/Framework/Storage/StorageProvider.cs index c6f8bac1..1104df89 100644 --- a/src/SMAPI.Web/Framework/Storage/StorageProvider.cs +++ b/src/SMAPI.Web/Framework/Storage/StorageProvider.cs @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Web.Framework.Storage // fetch file Response<BlobDownloadInfo> response = await blob.DownloadAsync(); using BlobDownloadInfo result = response.Value; - using StreamReader reader = new StreamReader(result.Content); + using StreamReader reader = new(result.Content); DateTimeOffset expiry = result.Details.LastModified + TimeSpan.FromDays(this.ExpiryDays); string content = this.GzipHelper.DecompressString(reader.ReadToEnd()); @@ -130,7 +130,7 @@ namespace StardewModdingAPI.Web.Framework.Storage else { // get file - FileInfo file = new FileInfo(this.GetDevFilePath(id)); + FileInfo file = new(this.GetDevFilePath(id)); if (file.Exists && file.LastWriteTimeUtc.AddDays(this.ExpiryDays) < DateTime.UtcNow) // expired file.Delete(); if (!file.Exists) diff --git a/src/SMAPI.Web/ViewModels/LogParserModel.cs b/src/SMAPI.Web/ViewModels/LogParserModel.cs index 0b6d7722..5aa2fd92 100644 --- a/src/SMAPI.Web/ViewModels/LogParserModel.cs +++ b/src/SMAPI.Web/ViewModels/LogParserModel.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI.Web.ViewModels ** Fields *********/ /// <summary>A regex pattern matching characters to remove from a mod name to create the slug ID.</summary> - private readonly Regex SlugInvalidCharPattern = new Regex("[^a-z0-9]", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private readonly Regex SlugInvalidCharPattern = new("[^a-z0-9]", RegexOptions.Compiled | RegexOptions.IgnoreCase); /********* diff --git a/src/SMAPI/Context.cs b/src/SMAPI/Context.cs index a745592c..4fbc9c42 100644 --- a/src/SMAPI/Context.cs +++ b/src/SMAPI/Context.cs @@ -14,10 +14,10 @@ namespace StardewModdingAPI ** Fields *********/ /// <summary>Whether the player has loaded a save and the world has finished initializing.</summary> - private static readonly PerScreen<bool> IsWorldReadyForScreen = new PerScreen<bool>(); + private static readonly PerScreen<bool> IsWorldReadyForScreen = new(); /// <summary>The current stage in the game's loading process.</summary> - private static readonly PerScreen<LoadStage> LoadStageForScreen = new PerScreen<LoadStage>(); + private static readonly PerScreen<LoadStage> LoadStageForScreen = new(); /// <summary>Whether a player save has been loaded.</summary> internal static bool IsSaveLoaded => Game1.hasLoadedGame && !(Game1.activeClickableMenu is TitleMenu); diff --git a/src/SMAPI/Framework/CommandManager.cs b/src/SMAPI/Framework/CommandManager.cs index ff540ad8..a7b64cb7 100644 --- a/src/SMAPI/Framework/CommandManager.cs +++ b/src/SMAPI/Framework/CommandManager.cs @@ -166,7 +166,7 @@ namespace StardewModdingAPI.Framework { bool inQuotes = false; IList<string> args = new List<string>(); - StringBuilder currentArg = new StringBuilder(); + StringBuilder currentArg = new(); foreach (char ch in input) { if (ch == '"') diff --git a/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs b/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs index 45b34556..643267ce 100644 --- a/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs +++ b/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs @@ -30,7 +30,7 @@ namespace StardewModdingAPI.Framework.Commands { SearchResult[] matches = this.FilterPatches(args).OrderBy(p => p.MethodName).ToArray(); - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); if (!matches.Any()) result.AppendLine("No current patches match your search."); diff --git a/src/SMAPI/Framework/Content/AssetDataForMap.cs b/src/SMAPI/Framework/Content/AssetDataForMap.cs index 26e4986e..0458f80a 100644 --- a/src/SMAPI/Framework/Content/AssetDataForMap.cs +++ b/src/SMAPI/Framework/Content/AssetDataForMap.cs @@ -96,8 +96,8 @@ namespace StardewModdingAPI.Framework.Content for (int y = 0; y < sourceArea.Value.Height; y++) { // calculate tile positions - Point sourcePos = new Point(sourceArea.Value.X + x, sourceArea.Value.Y + y); - Point targetPos = new Point(targetArea.Value.X + x, targetArea.Value.Y + y); + Point sourcePos = new(sourceArea.Value.X + x, sourceArea.Value.Y + y); + Point targetPos = new(targetArea.Value.X + x, targetArea.Value.Y + y); // replace tiles on target-only layers if (replaceAll) diff --git a/src/SMAPI/Framework/DeprecationManager.cs b/src/SMAPI/Framework/DeprecationManager.cs index fc1b434b..ad6a3677 100644 --- a/src/SMAPI/Framework/DeprecationManager.cs +++ b/src/SMAPI/Framework/DeprecationManager.cs @@ -11,7 +11,7 @@ namespace StardewModdingAPI.Framework ** Fields *********/ /// <summary>The deprecations which have already been logged (as 'mod name::noun phrase::version').</summary> - private readonly HashSet<string> LoggedDeprecations = new HashSet<string>(StringComparer.OrdinalIgnoreCase); + private readonly HashSet<string> LoggedDeprecations = new(StringComparer.OrdinalIgnoreCase); /// <summary>Encapsulates monitoring and logging for a given module.</summary> private readonly IMonitor Monitor; diff --git a/src/SMAPI/Framework/Events/ManagedEvent.cs b/src/SMAPI/Framework/Events/ManagedEvent.cs index 154ef659..1c8b9d04 100644 --- a/src/SMAPI/Framework/Events/ManagedEvent.cs +++ b/src/SMAPI/Framework/Events/ManagedEvent.cs @@ -18,7 +18,7 @@ namespace StardewModdingAPI.Framework.Events protected readonly ModRegistry ModRegistry; /// <summary>The underlying event handlers.</summary> - private readonly List<ManagedEventHandler<TEventArgs>> Handlers = new List<ManagedEventHandler<TEventArgs>>(); + private readonly List<ManagedEventHandler<TEventArgs>> Handlers = new(); /// <summary>A cached snapshot of <see cref="Handlers"/>, or <c>null</c> to rebuild it next raise.</summary> private ManagedEventHandler<TEventArgs>[] CachedHandlers = Array.Empty<ManagedEventHandler<TEventArgs>>(); diff --git a/src/SMAPI/Framework/Input/KeyboardStateBuilder.cs b/src/SMAPI/Framework/Input/KeyboardStateBuilder.cs index eadb7a8a..09bc48b6 100644 --- a/src/SMAPI/Framework/Input/KeyboardStateBuilder.cs +++ b/src/SMAPI/Framework/Input/KeyboardStateBuilder.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI.Framework.Input private KeyboardState? State; /// <summary>The pressed buttons.</summary> - private readonly HashSet<Keys> PressedButtons = new HashSet<Keys>(); + private readonly HashSet<Keys> PressedButtons = new(); /********* diff --git a/src/SMAPI/Framework/Input/SInputState.cs b/src/SMAPI/Framework/Input/SInputState.cs index a8d1f371..5ff7432b 100644 --- a/src/SMAPI/Framework/Input/SInputState.cs +++ b/src/SMAPI/Framework/Input/SInputState.cs @@ -21,10 +21,10 @@ namespace StardewModdingAPI.Framework.Input private Vector2? LastPlayerTile; /// <summary>The buttons to press until the game next handles input.</summary> - private readonly HashSet<SButton> CustomPressedKeys = new HashSet<SButton>(); + private readonly HashSet<SButton> CustomPressedKeys = new(); /// <summary>The buttons to consider released until the actual button is released.</summary> - private readonly HashSet<SButton> CustomReleasedKeys = new HashSet<SButton>(); + private readonly HashSet<SButton> CustomReleasedKeys = new(); /// <summary>Whether there are new overrides in <see cref="CustomPressedKeys"/> or <see cref="CustomReleasedKeys"/> that haven't been applied to the previous state.</summary> private bool HasNewOverrides; @@ -72,7 +72,7 @@ namespace StardewModdingAPI.Framework.Input var controller = new GamePadStateBuilder(base.GetGamePadState()); var keyboard = new KeyboardStateBuilder(base.GetKeyboardState()); var mouse = new MouseStateBuilder(base.GetMouseState()); - Vector2 cursorAbsolutePos = new Vector2((mouse.X * zoomMultiplier) + Game1.viewport.X, (mouse.Y * zoomMultiplier) + Game1.viewport.Y); + Vector2 cursorAbsolutePos = new((mouse.X * zoomMultiplier) + Game1.viewport.X, (mouse.Y * zoomMultiplier) + Game1.viewport.Y); Vector2? playerTilePos = Context.IsPlayerFree ? Game1.player.getTileLocation() : (Vector2?)null; HashSet<SButton> reallyDown = new HashSet<SButton>(this.GetPressedButtons(keyboard, mouse, controller)); @@ -203,8 +203,8 @@ namespace StardewModdingAPI.Framework.Input /// <param name="zoomMultiplier">The multiplier applied to pixel coordinates to adjust them for pixel zoom.</param> private CursorPosition GetCursorPosition(MouseState mouseState, Vector2 absolutePixels, float zoomMultiplier) { - Vector2 screenPixels = new Vector2(mouseState.X * zoomMultiplier, mouseState.Y * zoomMultiplier); - Vector2 tile = new Vector2((int)((Game1.viewport.X + screenPixels.X) / Game1.tileSize), (int)((Game1.viewport.Y + screenPixels.Y) / Game1.tileSize)); + Vector2 screenPixels = new(mouseState.X * zoomMultiplier, mouseState.Y * zoomMultiplier); + Vector2 tile = new((int)((Game1.viewport.X + screenPixels.X) / Game1.tileSize), (int)((Game1.viewport.Y + screenPixels.Y) / Game1.tileSize)); Vector2 grabTile = (Game1.mouseCursorTransparency > 0 && Utility.tileWithinRadiusOfPlayer((int)tile.X, (int)tile.Y, 1, Game1.player)) // derived from Game1.pressActionButton ? tile : Game1.player.GetGrabTile(); diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index cb5fa2ae..4480f4e8 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -36,13 +36,13 @@ namespace StardewModdingAPI.Framework.ModLoading private readonly AssemblyDefinitionResolver AssemblyDefinitionResolver; /// <summary>Provides assembly symbol readers for Mono.Cecil.</summary> - private readonly SymbolReaderProvider SymbolReaderProvider = new SymbolReaderProvider(); + private readonly SymbolReaderProvider SymbolReaderProvider = new(); /// <summary>Provides assembly symbol writers for Mono.Cecil.</summary> - private readonly SymbolWriterProvider SymbolWriterProvider = new SymbolWriterProvider(); + private readonly SymbolWriterProvider SymbolWriterProvider = new(); /// <summary>The objects to dispose as part of this instance.</summary> - private readonly HashSet<IDisposable> Disposables = new HashSet<IDisposable>(); + private readonly HashSet<IDisposable> Disposables = new(); /// <summary>Whether to rewrite mods for compatibility.</summary> private readonly bool RewriteMods; @@ -141,8 +141,8 @@ namespace StardewModdingAPI.Framework.ModLoading this.Monitor.Log($" Loading {assembly.File.Name} (rewritten)...", LogLevel.Trace); // load assembly - using MemoryStream outAssemblyStream = new MemoryStream(); - using MemoryStream outSymbolStream = new MemoryStream(); + using MemoryStream outAssemblyStream = new(); + using MemoryStream outSymbolStream = new(); assembly.Definition.Write(outAssemblyStream, new WriterParameters { WriteSymbols = true, SymbolStream = outSymbolStream, SymbolWriterProvider = this.SymbolWriterProvider }); byte[] bytes = outAssemblyStream.ToArray(); lastAssembly = Assembly.Load(bytes, outSymbolStream.ToArray()); @@ -241,7 +241,7 @@ namespace StardewModdingAPI.Framework.ModLoading try { // read assembly with symbols - FileInfo symbolsFile = new FileInfo(Path.Combine(Path.GetDirectoryName(file.FullName)!, Path.GetFileNameWithoutExtension(file.FullName)) + ".pdb"); + FileInfo symbolsFile = new(Path.Combine(Path.GetDirectoryName(file.FullName)!, Path.GetFileNameWithoutExtension(file.FullName)) + ".pdb"); if (symbolsFile.Exists) this.SymbolReaderProvider.TryAddSymbolData(file.Name, () => this.TrackForDisposal(symbolsFile.OpenRead())); assembly = this.TrackForDisposal(AssemblyDefinition.ReadAssembly(readStream, new ReaderParameters(ReadingMode.Immediate) { AssemblyResolver = assemblyResolver, InMemory = true, ReadSymbols = true, SymbolReaderProvider = this.SymbolReaderProvider })); @@ -266,7 +266,7 @@ namespace StardewModdingAPI.Framework.ModLoading // yield referenced assemblies foreach (AssemblyNameReference dependency in assembly.MainModule.AssemblyReferences) { - FileInfo dependencyFile = new FileInfo(Path.Combine(file.Directory.FullName, $"{dependency.Name}.dll")); + FileInfo dependencyFile = new(Path.Combine(file.Directory.FullName, $"{dependency.Name}.dll")); foreach (AssemblyParseResult result in this.GetReferencedLocalAssemblies(dependencyFile, visitedAssemblyNames, assemblyResolver)) yield return result; } @@ -333,7 +333,7 @@ namespace StardewModdingAPI.Framework.ModLoading // find or rewrite code IInstructionHandler[] handlers = new InstructionMetadata().GetHandlers(this.ParanoidMode, platformChanged, this.RewriteMods).ToArray(); - RecursiveRewriter rewriter = new RecursiveRewriter( + RecursiveRewriter rewriter = new( module: module, rewriteModule: curModule => { diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index 4b05d1e5..e3386f75 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -401,7 +401,7 @@ namespace StardewModdingAPI.Framework.ModLoading { foreach (string modRootPath in Directory.GetDirectories(rootPath)) { - DirectoryInfo directory = new DirectoryInfo(modRootPath); + DirectoryInfo directory = new(modRootPath); // if a folder only contains another folder, check the inner folder instead while (!directory.GetFiles().Any() && directory.GetDirectories().Length == 1) diff --git a/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs b/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs index 44074337..d28c4a22 100644 --- a/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs +++ b/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs @@ -16,7 +16,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Symbols private readonly ISymbolReaderProvider BaseProvider = new DefaultSymbolReaderProvider(throwIfNoSymbol: false); /// <summary>The symbol data loaded by absolute assembly path.</summary> - private readonly Dictionary<string, Stream> SymbolsByAssemblyPath = new Dictionary<string, Stream>(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary<string, Stream> SymbolsByAssemblyPath = new(StringComparer.OrdinalIgnoreCase); /********* diff --git a/src/SMAPI/Framework/ModRegistry.cs b/src/SMAPI/Framework/ModRegistry.cs index ef389337..99548cf8 100644 --- a/src/SMAPI/Framework/ModRegistry.cs +++ b/src/SMAPI/Framework/ModRegistry.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Framework ** Fields *********/ /// <summary>The registered mod data.</summary> - private readonly List<IModMetadata> Mods = new List<IModMetadata>(); + private readonly List<IModMetadata> Mods = new(); /// <summary>An assembly full name => mod lookup.</summary> private readonly IDictionary<string, IModMetadata> ModNamesByAssembly = new Dictionary<string, IModMetadata>(); @@ -94,7 +94,7 @@ namespace StardewModdingAPI.Framework public IModMetadata GetFromStack() { // get stack frames - StackTrace stack = new StackTrace(); + StackTrace stack = new(); StackFrame[] frames = stack.GetFrames(); if (frames == null) return null; diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index 9174aea6..35180df2 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -26,7 +26,7 @@ namespace StardewModdingAPI.Framework.Models }; /// <summary>The default values for <see cref="SuppressUpdateChecks"/>, to log changes if different.</summary> - private static readonly HashSet<string> DefaultSuppressUpdateChecks = new HashSet<string>(StringComparer.OrdinalIgnoreCase) + private static readonly HashSet<string> DefaultSuppressUpdateChecks = new(StringComparer.OrdinalIgnoreCase) { "SMAPI.ConsoleCommands", "SMAPI.ErrorHandler", diff --git a/src/SMAPI/Framework/Networking/SGalaxyNetServer.cs b/src/SMAPI/Framework/Networking/SGalaxyNetServer.cs index ac9cf313..71e11576 100644 --- a/src/SMAPI/Framework/Networking/SGalaxyNetServer.cs +++ b/src/SMAPI/Framework/Networking/SGalaxyNetServer.cs @@ -45,8 +45,8 @@ namespace StardewModdingAPI.Framework.Networking [SuppressMessage("ReSharper", "AccessToDisposedClosure", Justification = "The callback is invoked synchronously.")] protected override void onReceiveMessage(GalaxyID peer, Stream messageStream) { - using IncomingMessage message = new IncomingMessage(); - using BinaryReader reader = new BinaryReader(messageStream); + using IncomingMessage message = new(); + using BinaryReader reader = new(messageStream); message.Read(reader); ulong peerID = peer.ToUint64(); // note: GalaxyID instances get reused, so need to store the underlying ID instead @@ -57,7 +57,7 @@ namespace StardewModdingAPI.Framework.Networking else if (message.MessageType == StardewValley.Multiplayer.playerIntroduction) { NetFarmerRoot farmer = this.Multiplayer.readFarmer(message.Reader); - GalaxyID capturedPeer = new GalaxyID(peerID); + GalaxyID capturedPeer = new(peerID); this.gameServer.checkFarmhandRequest(Convert.ToString(peerID), this.getConnectionId(peer), farmer, msg => this.sendMessage(capturedPeer, msg), () => this.peers[farmer.Value.UniqueMultiplayerID] = capturedPeer.ToUint64()); } }); diff --git a/src/SMAPI/Framework/Networking/SLidgrenServer.cs b/src/SMAPI/Framework/Networking/SLidgrenServer.cs index 05c8b872..ff871e64 100644 --- a/src/SMAPI/Framework/Networking/SLidgrenServer.cs +++ b/src/SMAPI/Framework/Networking/SLidgrenServer.cs @@ -44,9 +44,9 @@ namespace StardewModdingAPI.Framework.Networking { // add hook to call multiplayer core NetConnection peer = rawMessage.SenderConnection; - using IncomingMessage message = new IncomingMessage(); + using IncomingMessage message = new(); using Stream readStream = new NetBufferReadStream(rawMessage); - using BinaryReader reader = new BinaryReader(readStream); + using BinaryReader reader = new(readStream); while (rawMessage.LengthBits - rawMessage.Position >= 8) { diff --git a/src/SMAPI/Framework/Reflection/Reflector.cs b/src/SMAPI/Framework/Reflection/Reflector.cs index 889c7ed6..3a93ab5d 100644 --- a/src/SMAPI/Framework/Reflection/Reflector.cs +++ b/src/SMAPI/Framework/Reflection/Reflector.cs @@ -13,7 +13,7 @@ namespace StardewModdingAPI.Framework.Reflection ** Fields *********/ /// <summary>The cached fields and methods found via reflection.</summary> - private readonly MemoryCache Cache = new MemoryCache(typeof(Reflector).FullName); + private readonly MemoryCache Cache = new(typeof(Reflector).FullName); /// <summary>The sliding cache expiration time.</summary> private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5); @@ -268,7 +268,7 @@ namespace StardewModdingAPI.Framework.Reflection // fetch & cache new value TMemberInfo result = fetch(); - CacheEntry cacheEntry = new CacheEntry(result != null, result); + CacheEntry cacheEntry = new(result != null, result); this.Cache.Add(key, cacheEntry, new CacheItemPolicy { SlidingExpiration = this.SlidingCacheExpiry }); return result; } diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 104cf330..989b59d8 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -37,7 +37,7 @@ namespace StardewModdingAPI.Framework private readonly EventManager Events; /// <summary>The maximum number of consecutive attempts SMAPI should make to recover from a draw error.</summary> - private readonly Countdown DrawCrashTimer = new Countdown(60); // 60 ticks = roughly one second + private readonly Countdown DrawCrashTimer = new(60); // 60 ticks = roughly one second /// <summary>Simplifies access to private game code.</summary> private readonly Reflector Reflection; @@ -71,14 +71,14 @@ namespace StardewModdingAPI.Framework public WatcherCore Watchers { get; private set; } /// <summary>A snapshot of the current <see cref="Watchers"/> state.</summary> - public WatcherSnapshot WatcherSnapshot { get; } = new WatcherSnapshot(); + public WatcherSnapshot WatcherSnapshot { get; } = new(); /// <summary>Whether the current update tick is the first one for this instance.</summary> public bool IsFirstTick = true; /// <summary>The number of ticks until SMAPI should notify mods that the game has loaded.</summary> /// <remarks>Skipping a few frames ensures the game finishes initializing the world before mods try to change it.</remarks> - public Countdown AfterLoadTimer { get; } = new Countdown(5); + public Countdown AfterLoadTimer { get; } = new(5); /// <summary>Whether the game is saving and SMAPI has already raised <see cref="IGameLoopEvents.Saving"/>.</summary> public bool IsBetweenSaveEvents { get; set; } @@ -624,7 +624,7 @@ namespace StardewModdingAPI.Framework if (tile != null) { Vector2 vector_draw_position = Game1.GlobalToLocal(Game1.viewport, tile_position * 64f); - Location draw_location = new Location((int)vector_draw_position.X, (int)vector_draw_position.Y); + Location draw_location = new((int)vector_draw_position.X, (int)vector_draw_position.Y); Game1.mapDisplayDevice.DrawTile(tile, draw_location, (tile_position.Y * 64f - 1f) / 10000f); } } diff --git a/src/SMAPI/Framework/SGameRunner.cs b/src/SMAPI/Framework/SGameRunner.cs index b816bb7c..81cac145 100644 --- a/src/SMAPI/Framework/SGameRunner.cs +++ b/src/SMAPI/Framework/SGameRunner.cs @@ -93,7 +93,7 @@ namespace StardewModdingAPI.Framework /// <param name="instanceIndex">The instance index.</param> public override Game1 CreateGameInstance(PlayerIndex playerIndex = PlayerIndex.One, int instanceIndex = 0) { - SInputState inputState = new SInputState(); + SInputState inputState = new(); return new SGame(playerIndex, instanceIndex, this.Monitor, this.Reflection, this.Events, inputState, this.ModHooks, this.Multiplayer, this.ExitGameImmediately, this.OnPlayerInstanceUpdating, this.OnGameContentLoaded); } diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index 5956b63f..3981e4e5 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -56,10 +56,10 @@ namespace StardewModdingAPI.Framework private readonly bool LogNetworkTraffic; /// <summary>The backing field for <see cref="Peers"/>.</summary> - private readonly PerScreen<IDictionary<long, MultiplayerPeer>> PeersImpl = new PerScreen<IDictionary<long, MultiplayerPeer>>(() => new Dictionary<long, MultiplayerPeer>()); + private readonly PerScreen<IDictionary<long, MultiplayerPeer>> PeersImpl = new(() => new Dictionary<long, MultiplayerPeer>()); /// <summary>The backing field for <see cref="HostPeer"/>.</summary> - private readonly PerScreen<MultiplayerPeer> HostPeerImpl = new PerScreen<MultiplayerPeer>(); + private readonly PerScreen<MultiplayerPeer> HostPeerImpl = new(); /********* @@ -196,7 +196,7 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Received context for farmhand {message.FarmerID} running {(model != null ? $"SMAPI {model.ApiVersion} with {model.Mods.Length} mods" : "vanilla")}.", LogLevel.Trace); // store peer - MultiplayerPeer newPeer = new MultiplayerPeer( + MultiplayerPeer newPeer = new( playerID: message.FarmerID, screenID: this.GetScreenId(message.FarmerID), model: model, @@ -244,7 +244,7 @@ namespace StardewModdingAPI.Framework if (!this.Peers.ContainsKey(message.FarmerID)) { this.Monitor.Log($"Received connection for vanilla player {message.FarmerID}.", LogLevel.Trace); - MultiplayerPeer peer = new MultiplayerPeer( + MultiplayerPeer peer = new( playerID: message.FarmerID, screenID: this.GetScreenId(message.FarmerID), model: null, @@ -292,7 +292,7 @@ namespace StardewModdingAPI.Framework this.Monitor.Log($"Received context for {(model?.IsHost == true ? "host" : "farmhand")} {message.FarmerID} running {(model != null ? $"SMAPI {model.ApiVersion} with {model.Mods.Length} mods" : "vanilla")}.", LogLevel.Trace); // store peer - MultiplayerPeer peer = new MultiplayerPeer( + MultiplayerPeer peer = new( playerID: message.FarmerID, screenID: this.GetScreenId(message.FarmerID), model: model, @@ -420,7 +420,7 @@ namespace StardewModdingAPI.Framework } // get data to send - ModMessageModel model = new ModMessageModel( + ModMessageModel model = new( fromPlayerID: Game1.player.UniqueMultiplayerID, fromModID: fromModID, toModIDs: toModIDs, @@ -513,7 +513,7 @@ namespace StardewModdingAPI.Framework // forward to other players if (Context.IsMainPlayer && playerIDs.Any(p => p != Game1.player.UniqueMultiplayerID)) { - ModMessageModel newModel = new ModMessageModel(model); + ModMessageModel newModel = new(model); foreach (long playerID in playerIDs) { if (playerID != Game1.player.UniqueMultiplayerID && playerID != model.FromPlayerID && this.Peers.TryGetValue(playerID, out MultiplayerPeer peer)) @@ -544,7 +544,7 @@ namespace StardewModdingAPI.Framework /// <summary>Get the fields to include in a context sync message sent to other players.</summary> private object[] GetContextSyncMessageFields() { - RemoteContextModel model = new RemoteContextModel + RemoteContextModel model = new() { IsHost = Context.IsWorldReady && Context.IsMainPlayer, Platform = Constants.TargetPlatform, @@ -571,7 +571,7 @@ namespace StardewModdingAPI.Framework if (!peer.HasSmapi) return new object[] { "{}" }; - RemoteContextModel model = new RemoteContextModel + RemoteContextModel model = new() { IsHost = peer.IsHost, Platform = peer.Platform.Value, diff --git a/src/SMAPI/Framework/Singleton.cs b/src/SMAPI/Framework/Singleton.cs index 399a8bf0..1bf318c4 100644 --- a/src/SMAPI/Framework/Singleton.cs +++ b/src/SMAPI/Framework/Singleton.cs @@ -5,6 +5,6 @@ namespace StardewModdingAPI.Framework internal static class Singleton<T> where T : new() { /// <summary>The singleton instance.</summary> - public static T Instance { get; } = new T(); + public static T Instance { get; } = new(); } } diff --git a/src/SMAPI/Framework/SnapshotListDiff.cs b/src/SMAPI/Framework/SnapshotListDiff.cs index 2d0efa0d..1c3ebfba 100644 --- a/src/SMAPI/Framework/SnapshotListDiff.cs +++ b/src/SMAPI/Framework/SnapshotListDiff.cs @@ -11,10 +11,10 @@ namespace StardewModdingAPI.Framework ** Fields *********/ /// <summary>The removed values.</summary> - private readonly List<T> RemovedImpl = new List<T>(); + private readonly List<T> RemovedImpl = new(); /// <summary>The added values.</summary> - private readonly List<T> AddedImpl = new List<T>(); + private readonly List<T> AddedImpl = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/ChestTracker.cs b/src/SMAPI/Framework/StateTracking/ChestTracker.cs index 65f58ee7..56aeeb3c 100644 --- a/src/SMAPI/Framework/StateTracking/ChestTracker.cs +++ b/src/SMAPI/Framework/StateTracking/ChestTracker.cs @@ -18,10 +18,10 @@ namespace StardewModdingAPI.Framework.StateTracking private readonly IDictionary<Item, int> StackSizes; /// <summary>Items added since the last update.</summary> - private readonly HashSet<Item> Added = new HashSet<Item>(new ObjectReferenceComparer<Item>()); + private readonly HashSet<Item> Added = new(new ObjectReferenceComparer<Item>()); /// <summary>Items removed since the last update.</summary> - private readonly HashSet<Item> Removed = new HashSet<Item>(new ObjectReferenceComparer<Item>()); + private readonly HashSet<Item> Removed = new(new ObjectReferenceComparer<Item>()); /// <summary>The underlying inventory watcher.</summary> private readonly ICollectionWatcher<Item> InventoryWatcher; diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs index 32ec8c7e..256370ce 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableListWatcher.cs @@ -17,10 +17,10 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers private HashSet<TValue> LastValues; /// <summary>The pairs added since the last reset.</summary> - private readonly List<TValue> AddedImpl = new List<TValue>(); + private readonly List<TValue> AddedImpl = new(); /// <summary>The pairs removed since the last reset.</summary> - private readonly List<TValue> RemovedImpl = new List<TValue>(); + private readonly List<TValue> RemovedImpl = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ImmutableCollectionWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ImmutableCollectionWatcher.cs index 009e0282..84340fbf 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ImmutableCollectionWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ImmutableCollectionWatcher.cs @@ -11,7 +11,7 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers ** Accessors *********/ /// <summary>A singleton collection watcher instance.</summary> - public static ImmutableCollectionWatcher<TValue> Instance { get; } = new ImmutableCollectionWatcher<TValue>(); + public static ImmutableCollectionWatcher<TValue> Instance { get; } = new(); /// <summary>Whether the collection changed since the last reset.</summary> public bool IsChanged { get; } = false; diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/NetCollectionWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/NetCollectionWatcher.cs index 21e84c47..676c9fb4 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/NetCollectionWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/NetCollectionWatcher.cs @@ -15,10 +15,10 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers private readonly NetCollection<TValue> Field; /// <summary>The pairs added since the last reset.</summary> - private readonly List<TValue> AddedImpl = new List<TValue>(); + private readonly List<TValue> AddedImpl = new(); /// <summary>The pairs removed since the last reset.</summary> - private readonly List<TValue> RemovedImpl = new List<TValue>(); + private readonly List<TValue> RemovedImpl = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs index c29d2783..3e9fa8b1 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs @@ -16,13 +16,13 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers private readonly ObservableCollection<TValue> Field; /// <summary>The pairs added since the last reset.</summary> - private readonly List<TValue> AddedImpl = new List<TValue>(); + private readonly List<TValue> AddedImpl = new(); /// <summary>The pairs removed since the last reset.</summary> - private readonly List<TValue> RemovedImpl = new List<TValue>(); + private readonly List<TValue> RemovedImpl = new(); /// <summary>The previous values as of the last update.</summary> - private readonly List<TValue> PreviousValues = new List<TValue>(); + private readonly List<TValue> PreviousValues = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/LocationTracker.cs b/src/SMAPI/Framework/StateTracking/LocationTracker.cs index 748e4ecc..f86f86ee 100644 --- a/src/SMAPI/Framework/StateTracking/LocationTracker.cs +++ b/src/SMAPI/Framework/StateTracking/LocationTracker.cs @@ -19,7 +19,7 @@ namespace StardewModdingAPI.Framework.StateTracking ** Fields *********/ /// <summary>The underlying watchers.</summary> - private readonly List<IWatcher> Watchers = new List<IWatcher>(); + private readonly List<IWatcher> Watchers = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/PlayerTracker.cs b/src/SMAPI/Framework/StateTracking/PlayerTracker.cs index cf49a7c1..3d470b5c 100644 --- a/src/SMAPI/Framework/StateTracking/PlayerTracker.cs +++ b/src/SMAPI/Framework/StateTracking/PlayerTracker.cs @@ -24,7 +24,7 @@ namespace StardewModdingAPI.Framework.StateTracking private GameLocation LastValidLocation; /// <summary>The underlying watchers.</summary> - private readonly List<IWatcher> Watchers = new List<IWatcher>(); + private readonly List<IWatcher> Watchers = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs index 6c9cc4f5..2563d10c 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs @@ -17,25 +17,25 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots public GameLocation Location { get; } /// <summary>Tracks added or removed buildings.</summary> - public SnapshotListDiff<Building> Buildings { get; } = new SnapshotListDiff<Building>(); + public SnapshotListDiff<Building> Buildings { get; } = new(); /// <summary>Tracks added or removed debris.</summary> - public SnapshotListDiff<Debris> Debris { get; } = new SnapshotListDiff<Debris>(); + public SnapshotListDiff<Debris> Debris { get; } = new(); /// <summary>Tracks added or removed large terrain features.</summary> - public SnapshotListDiff<LargeTerrainFeature> LargeTerrainFeatures { get; } = new SnapshotListDiff<LargeTerrainFeature>(); + public SnapshotListDiff<LargeTerrainFeature> LargeTerrainFeatures { get; } = new(); /// <summary>Tracks added or removed NPCs.</summary> - public SnapshotListDiff<NPC> Npcs { get; } = new SnapshotListDiff<NPC>(); + public SnapshotListDiff<NPC> Npcs { get; } = new(); /// <summary>Tracks added or removed objects.</summary> - public SnapshotListDiff<KeyValuePair<Vector2, Object>> Objects { get; } = new SnapshotListDiff<KeyValuePair<Vector2, Object>>(); + public SnapshotListDiff<KeyValuePair<Vector2, Object>> Objects { get; } = new(); /// <summary>Tracks added or removed terrain features.</summary> - public SnapshotListDiff<KeyValuePair<Vector2, TerrainFeature>> TerrainFeatures { get; } = new SnapshotListDiff<KeyValuePair<Vector2, TerrainFeature>>(); + public SnapshotListDiff<KeyValuePair<Vector2, TerrainFeature>> TerrainFeatures { get; } = new(); /// <summary>Tracks added or removed furniture.</summary> - public SnapshotListDiff<Furniture> Furniture { get; } = new SnapshotListDiff<Furniture>(); + public SnapshotListDiff<Furniture> Furniture { get; } = new(); /// <summary>Tracks changed chest inventories.</summary> public IDictionary<Chest, SnapshotItemListDiff> ChestItems { get; } = new Dictionary<Chest, SnapshotItemListDiff>(); diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs index 72f45a87..f3e42948 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs @@ -14,7 +14,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots ** Fields *********/ /// <summary>An empty item list diff.</summary> - private readonly SnapshotItemListDiff EmptyItemListDiff = new SnapshotItemListDiff(Array.Empty<Item>(), Array.Empty<Item>(), Array.Empty<ItemStackSizeChange>()); + private readonly SnapshotItemListDiff EmptyItemListDiff = new(Array.Empty<Item>(), Array.Empty<Item>(), Array.Empty<ItemStackSizeChange>()); /********* @@ -24,7 +24,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots public Farmer Player { get; } /// <summary>The player's current location.</summary> - public SnapshotDiff<GameLocation> Location { get; } = new SnapshotDiff<GameLocation>(); + public SnapshotDiff<GameLocation> Location { get; } = new(); /// <summary>Tracks changes to the player's skill levels.</summary> public IDictionary<SkillType, SnapshotDiff<int>> Skills { get; } = diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs index cf51e040..afea7fb4 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs @@ -11,31 +11,31 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots ** Accessors *********/ /// <summary>Tracks changes to the window size.</summary> - public SnapshotDiff<Point> WindowSize { get; } = new SnapshotDiff<Point>(); + public SnapshotDiff<Point> WindowSize { get; } = new(); /// <summary>Tracks changes to the current player.</summary> public PlayerSnapshot CurrentPlayer { get; private set; } /// <summary>Tracks changes to the time of day (in 24-hour military format).</summary> - public SnapshotDiff<int> Time { get; } = new SnapshotDiff<int>(); + public SnapshotDiff<int> Time { get; } = new(); /// <summary>Tracks changes to the save ID.</summary> - public SnapshotDiff<ulong> SaveID { get; } = new SnapshotDiff<ulong>(); + public SnapshotDiff<ulong> SaveID { get; } = new(); /// <summary>Tracks changes to the game's locations.</summary> - public WorldLocationsSnapshot Locations { get; } = new WorldLocationsSnapshot(); + public WorldLocationsSnapshot Locations { get; } = new(); /// <summary>Tracks changes to <see cref="Game1.activeClickableMenu"/>.</summary> - public SnapshotDiff<IClickableMenu> ActiveMenu { get; } = new SnapshotDiff<IClickableMenu>(); + public SnapshotDiff<IClickableMenu> ActiveMenu { get; } = new(); /// <summary>Tracks changes to the cursor position.</summary> - public SnapshotDiff<ICursorPosition> Cursor { get; } = new SnapshotDiff<ICursorPosition>(); + public SnapshotDiff<ICursorPosition> Cursor { get; } = new(); /// <summary>Tracks changes to the mouse wheel scroll.</summary> - public SnapshotDiff<int> MouseWheelScroll { get; } = new SnapshotDiff<int>(); + public SnapshotDiff<int> MouseWheelScroll { get; } = new(); /// <summary>Tracks changes to the content locale.</summary> - public SnapshotDiff<LocalizedContentManager.LanguageCode> Locale { get; } = new SnapshotDiff<LocalizedContentManager.LanguageCode>(); + public SnapshotDiff<LocalizedContentManager.LanguageCode> Locale { get; } = new(); /********* diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs index 73ed2d8f..7dee09ca 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs @@ -12,14 +12,14 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots ** Fields *********/ /// <summary>A map of tracked locations.</summary> - private readonly Dictionary<GameLocation, LocationSnapshot> LocationsDict = new Dictionary<GameLocation, LocationSnapshot>(new ObjectReferenceComparer<GameLocation>()); + private readonly Dictionary<GameLocation, LocationSnapshot> LocationsDict = new(new ObjectReferenceComparer<GameLocation>()); /********* ** Accessors *********/ /// <summary>Tracks changes to the location list.</summary> - public SnapshotListDiff<GameLocation> LocationList { get; } = new SnapshotListDiff<GameLocation>(); + public SnapshotListDiff<GameLocation> LocationList { get; } = new(); /// <summary>The tracked locations.</summary> public IEnumerable<LocationSnapshot> Locations => this.LocationsDict.Values; diff --git a/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs b/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs index 173438f1..cab1a94c 100644 --- a/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs +++ b/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs @@ -55,7 +55,7 @@ namespace MonoMod.Utils .GetType("System.RuntimeType+RuntimeTypeCache") ?.GetMethod("GetPropertyList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - private static readonly ConditionalWeakTable<Type, CacheFixEntry> _CacheFixed = new ConditionalWeakTable<Type, CacheFixEntry>(); + private static readonly ConditionalWeakTable<Type, CacheFixEntry> _CacheFixed = new(); public static void Apply() { @@ -144,7 +144,7 @@ namespace MonoMod.Utils continue; CacheFixEntry entry = _CacheFixed.GetValue(type, rt => { - CacheFixEntry entryNew = new CacheFixEntry(); + CacheFixEntry entryNew = new(); object cache; Array properties, fields; diff --git a/src/SMAPI/Framework/WatcherCore.cs b/src/SMAPI/Framework/WatcherCore.cs index 62a0c3b8..a1612e75 100644 --- a/src/SMAPI/Framework/WatcherCore.cs +++ b/src/SMAPI/Framework/WatcherCore.cs @@ -17,7 +17,7 @@ namespace StardewModdingAPI.Framework ** Fields *********/ /// <summary>The underlying watchers for convenience. These are accessible individually as separate properties.</summary> - private readonly List<IWatcher> Watchers = new List<IWatcher>(); + private readonly List<IWatcher> Watchers = new(); /********* diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index f2f65287..29f4be1b 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -199,7 +199,7 @@ namespace StardewModdingAPI } // load SMAPI - using SCore core = new SCore(modsPath, writeToConsole); + using SCore core = new(modsPath, writeToConsole); core.RunInteractively(); } |