From 05934c8157257f4a5b4ade014270dbb7fb0e05bc Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Dec 2024 10:26:04 +1100 Subject: [PATCH] remove some redundant variable assignments --- .../Projects/ProjectJsonProjectProvider.cs | 2 +- .../Utility/GetPackageReferenceUtility.cs | 4 +--- .../MSBuildStaticGraphRestore.cs | 2 +- .../AddPackageReferenceCommandRunner.cs | 2 +- .../Utility/TableParser.cs | 2 +- .../RestoreCommand/RestoreCommand.cs | 4 ++-- .../RestoreCommand/Utility/BuildAssetsUtils.cs | 7 ++----- .../Utility/MSBuildRestoreUtility.cs | 11 +++-------- .../PackagePreFetcher.cs | 2 +- .../Projects/MSBuildNuGetProject.cs | 3 +-- .../Utility/JsonConfigUtility.cs | 15 +++++---------- .../Utility/StreamUtility.cs | 6 +++--- .../NuGet.Packaging/PackagesConfigReader.cs | 11 ++++------- .../Signing/Archive/ReadOnlyBufferedStream.cs | 2 +- .../Rfc3161TimestampRequestFactory.cs | 7 ++----- .../Verification/PackageSignatureVerifier.cs | 2 +- .../JsonPackageSpecReader.cs | 2 +- .../PackagesLockFileUtilities.cs | 4 ++-- .../ODataServiceDocumentResourceV2Provider.cs | 3 +-- .../PackagesFolder/LocalPackageFileCache.cs | 18 +++++------------- .../NuGetv3LocalRepositoryUtility.cs | 4 +--- .../GetCredentialsRequestHandler.cs | 2 +- .../Resources/MetadataResourceV3.cs | 4 +--- .../NuGet.Versioning/VersionRange.cs | 4 +--- .../NuGet.Versioning/VersionRangeFactory.cs | 4 ++-- .../Commands/PushCommandTest.cs | 10 +++++----- .../ViewModels/PackageItemViewModelTests.cs | 4 +--- .../NuGet.Commands.FuncTest/UWPRestoreTests.cs | 2 +- .../NuGet.Packaging.Test/PackageBuilderTest.cs | 2 +- .../LockFileFormatTests.cs | 15 +++++++-------- .../SemVer201SpecTests.cs | 15 ++++++--------- 31 files changed, 66 insertions(+), 109 deletions(-) diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectJsonProjectProvider.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectJsonProjectProvider.cs index 23b6578b1a5..dd5527fa9bd 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectJsonProjectProvider.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectJsonProjectProvider.cs @@ -70,7 +70,7 @@ public NuGetProject TryCreateNuGetProject( // Treat projects with project.json as build integrated projects // Search for projectName.project.json first, then project.json // If the name cannot be determined, search only for project.json - string projectJsonPath = null; + string projectJsonPath; if (string.IsNullOrEmpty(projectNameFromMSBuildPath)) { projectJsonPath = Path.Combine(msbuildProjectFile.DirectoryName, diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/GetPackageReferenceUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/GetPackageReferenceUtility.cs index f16712770e0..a906e7b76ee 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/GetPackageReferenceUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/GetPackageReferenceUtility.cs @@ -67,8 +67,6 @@ internal static PackageIdentity UpdateResolvedVersion(LibraryDependency projectL /// Cached transitive package information internal static IReadOnlyList UpdateTransitiveDependencies(IList libraries, Dictionary installedPackages, Dictionary transitivePackages) { - NuGetVersion resolvedVersion = default; - var packageIdentities = new List(); // get the dependencies for this target framework @@ -80,7 +78,7 @@ internal static IReadOnlyList UpdateTransitiveDependencies(ILis // don't add transitive packages if they are not packages if (!installedPackages.ContainsKey(package.Name) && package.Type == LibraryType.Package.Value) { - resolvedVersion = package.Version ?? new NuGetVersion(0, 0, 0); + NuGetVersion resolvedVersion = package.Version ?? new NuGetVersion(0, 0, 0); var packageIdentity = new PackageIdentity(package.Name, resolvedVersion); transitivePackages[package.Name] = new ProjectInstalledPackage(new VersionRange(package.Version), packageIdentity); diff --git a/src/NuGet.Core/NuGet.Build.Tasks.Console/MSBuildStaticGraphRestore.cs b/src/NuGet.Core/NuGet.Build.Tasks.Console/MSBuildStaticGraphRestore.cs index 4955acdcf36..dea6cdd3f06 100644 --- a/src/NuGet.Core/NuGet.Build.Tasks.Console/MSBuildStaticGraphRestore.cs +++ b/src/NuGet.Core/NuGet.Build.Tasks.Console/MSBuildStaticGraphRestore.cs @@ -241,7 +241,7 @@ internal static string GetBinaryLoggerParameters(IEnvironmentVariableReader envi } // Default parameters - return binaryLoggerParameters = "LogFile=nuget.binlog"; + return "LogFile=nuget.binlog"; } /// diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommandRunner.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommandRunner.cs index 894795fa2ee..2b1fdef4091 100644 --- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommandRunner.cs +++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommandRunner.cs @@ -38,7 +38,7 @@ public async Task ExecuteCommand(PackageReferenceArgs packageReferenceArgs, packageReferenceArgs.Logger.LogWarning(string.Format(CultureInfo.CurrentCulture, Strings.Warn_AddPkgWithoutRestore)); - VersionRange versionRange = default; + VersionRange versionRange; if (packageReferenceArgs.NoVersion) { versionRange = packageReferenceArgs.Prerelease ? diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Utility/TableParser.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Utility/TableParser.cs index f7ebe70afd5..6a3bbdcc720 100644 --- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Utility/TableParser.cs +++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Utility/TableParser.cs @@ -93,7 +93,7 @@ internal static IEnumerable ToFormattedStringTable( var subsequentRow = new List(); for (var colIndex = 0; colIndex < valueSelectors.Length; colIndex++) { - var formattedDataCell = (FormattedCell)null; + FormattedCell formattedDataCell; if (columnQueues.TryGetValue(colIndex, out var thisColumnQueue)) // we have at least one remaining value for this column { formattedDataCell = thisColumnQueue.Dequeue(); diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreCommand.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreCommand.cs index db923840be7..b1dd850dfbc 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreCommand.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreCommand.cs @@ -490,8 +490,8 @@ private async Task> GenerateRestoreGraphsAsync(T CacheFile cacheFile, CancellationToken token) { - string assetFilePath = null; - string cacheFilePath = null; + string assetFilePath; + string cacheFilePath; var msbuildOutputFiles = Enumerable.Empty(); using (telemetry.StartIndependentInterval(CreateRestoreResultDuration)) diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/BuildAssetsUtils.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/BuildAssetsUtils.cs index 16e1350455f..58e359c423b 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/BuildAssetsUtils.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/BuildAssetsUtils.cs @@ -74,24 +74,21 @@ public static List GenerateMultiTargetFailureFiles( string propsPath, ProjectStyle restoreType) { - XDocument targetsXML = null; XDocument propsXML = null; // Create an error file for MSBuild to stop the build. - targetsXML = GenerateMultiTargetFrameworkWarning(); + XDocument targetsXML = GenerateMultiTargetFrameworkWarning(); if (restoreType == ProjectStyle.PackageReference) { propsXML = GenerateEmptyImportsFile(); } - var files = new List() + return new List() { new MSBuildOutputFile(propsPath, propsXML), new MSBuildOutputFile(targetsPath, targetsXML), }; - - return files; } private static string ReplacePathsWithMacros(string path, IEnvironmentVariableReader environmentVariableReader) diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs index 3416b53dbc3..c2726ab7cb8 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs @@ -969,20 +969,15 @@ private static bool IsType(this IMSBuildItem item, string type) private static NuGetVersion GetVersion(IMSBuildItem item) { var versionString = item.GetProperty("Version"); - NuGetVersion version = null; if (string.IsNullOrEmpty(versionString)) { // Default to 1.0.0 if the property does not exist - version = new NuGetVersion(1, 0, 0); - } - else - { - // Snapshot versions are not allowed in .NETCore - version = NuGetVersion.Parse(versionString); + return new NuGetVersion(1, 0, 0); } - return version; + // Snapshot versions are not allowed in .NETCore + return NuGetVersion.Parse(versionString); } public static void Dump(IEnumerable items, ILogger log) diff --git a/src/NuGet.Core/NuGet.PackageManagement/PackagePreFetcher.cs b/src/NuGet.Core/NuGet.PackageManagement/PackagePreFetcher.cs index d7c5f7bd296..3d4afe0a784 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/PackagePreFetcher.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/PackagePreFetcher.cs @@ -180,7 +180,7 @@ public static void LogFetchMessages( foreach (var fetchResult in preFetchTasks) { - string message = null; + string message; if (fetchResult.InPackagesFolder) { diff --git a/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs b/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs index a28ba19f842..e2ce2defd23 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Projects/MSBuildNuGetProject.cs @@ -654,8 +654,7 @@ public async Task> GetPackageSpecsAsync(DependencyGra return (new List(), null); } - PackageSpec packageSpec = null; - if (!context.PackageSpecCache.TryGetValue(ProjectSystem.ProjectFileFullPath, out packageSpec)) + if (!context.PackageSpecCache.TryGetValue(ProjectSystem.ProjectFileFullPath, out var packageSpec)) { packageSpec = new PackageSpec(new List { diff --git a/src/NuGet.Core/NuGet.PackageManagement/Utility/JsonConfigUtility.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/JsonConfigUtility.cs index e74ad27027b..951a40dd99c 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/JsonConfigUtility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/JsonConfigUtility.cs @@ -26,8 +26,7 @@ public static class JsonConfigUtility /// public static IEnumerable GetDependencies(JObject json) { - JToken node = null; - if (json.TryGetValue(DEPENDENCIES_TAG, out node)) + if (json.TryGetValue(DEPENDENCIES_TAG, out var node)) { foreach (var dependency in node) { @@ -96,8 +95,7 @@ public static void AddDependency(JObject json, PackageDependency dependency) JObject dependencySet = null; - JToken node = null; - if (json.TryGetValue(DEPENDENCIES_TAG, out node)) + if (json.TryGetValue(DEPENDENCIES_TAG, out var node)) { dependencySet = node as JObject; } @@ -121,8 +119,7 @@ public static void AddDependency(JObject json, PackageDependency dependency) /// public static void RemoveDependency(JObject json, string packageId) { - JToken node = null; - if (json.TryGetValue(DEPENDENCIES_TAG, out node)) + if (json.TryGetValue(DEPENDENCIES_TAG, out var node)) { foreach (var dependency in node.ToArray()) { @@ -142,8 +139,7 @@ public static IEnumerable GetFrameworks(JObject json) { var results = new List(); - JToken node = null; - if (json.TryGetValue(FRAMEWORKS_TAG, out node)) + if (json.TryGetValue(FRAMEWORKS_TAG, out var node)) { foreach (var frameworkNode in node.ToArray()) { @@ -172,8 +168,7 @@ public static void AddFramework(JObject json, NuGetFramework framework) JObject frameworkSet = null; - JToken node = null; - if (json.TryGetValue(FRAMEWORKS_TAG, out node)) + if (json.TryGetValue(FRAMEWORKS_TAG, out var node)) { frameworkSet = node as JObject; } diff --git a/src/NuGet.Core/NuGet.PackageManagement/Utility/StreamUtility.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/StreamUtility.cs index e77d6548c83..8488dbe1291 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/StreamUtility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/StreamUtility.cs @@ -42,8 +42,8 @@ public static bool ContentEquals(Stream stream, Stream otherStream) public static bool IsBinary(Stream stream) { // Quick and dirty trick to check if a stream represents binary content. - // We read the first 30 bytes. If there's a character 0 in those bytes, - // we assume this is a binary file. + // We read the first 30 bytes. If there's a character 0 in those bytes, + // we assume this is a binary file. var a = new byte[30]; var bytesRead = stream.Read(a, 0, 30); var byteZeroIndex = Array.FindIndex(a, 0, bytesRead, d => d == 0); @@ -104,7 +104,7 @@ private static bool CompareBinary(Stream stream, Stream otherStream) var buffer = new byte[4 * 1024]; var otherBuffer = new byte[4 * 1024]; - var bytesRead = 0; + int bytesRead; do { bytesRead = stream.Read(buffer, 0, buffer.Length); diff --git a/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs b/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs index 16c54985011..4dca8599c4f 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs @@ -134,7 +134,7 @@ public IEnumerable GetPackages() /// /// Reads all package node entries in the config. /// - /// If True validation will be performed to ensure that + /// If True validation will be performed to ensure that /// only one entry exists for each unique package id. public IEnumerable GetPackages(bool allowDuplicatePackageIds) { @@ -151,8 +151,7 @@ public IEnumerable GetPackages(bool allowDuplicatePackageIds) Strings.ErrorNullOrEmptyPackageId)); } - string version = null; - if (!PackagesConfig.TryGetAttribute(package, PackagesConfig.VersionAttributeName, out version) + if (!PackagesConfig.TryGetAttribute(package, PackagesConfig.VersionAttributeName, out var version) || String.IsNullOrEmpty(version)) { throw new PackagesConfigReaderException(string.Format( @@ -162,8 +161,7 @@ public IEnumerable GetPackages(bool allowDuplicatePackageIds) version)); } - NuGetVersion semver = null; - if (!NuGetVersion.TryParse(version, out semver)) + if (!NuGetVersion.TryParse(version, out var semver)) { throw new PackagesConfigReaderException(string.Format( CultureInfo.CurrentCulture, @@ -172,9 +170,8 @@ public IEnumerable GetPackages(bool allowDuplicatePackageIds) version)); } - string attributeValue = null; VersionRange allowedVersions = null; - if (PackagesConfig.TryGetAttribute(package, PackagesConfig.allowedVersionsAttributeName, out attributeValue)) + if (PackagesConfig.TryGetAttribute(package, PackagesConfig.allowedVersionsAttributeName, out var attributeValue)) { if (!VersionRange.TryParse(attributeValue, out allowedVersions)) { diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Archive/ReadOnlyBufferedStream.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Archive/ReadOnlyBufferedStream.cs index 74ff531f753..cc3cd7ada15 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Archive/ReadOnlyBufferedStream.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Archive/ReadOnlyBufferedStream.cs @@ -330,7 +330,7 @@ private void FillBuffer() _stream.Position = _bufferStartPosition; var totalBytesRead = 0; - var bytesRead = 0; + int bytesRead; var offset = 0; var count = _buffer.Length; diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequestFactory.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequestFactory.cs index d65d3bcfd7e..cd60513e735 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequestFactory.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequestFactory.cs @@ -23,9 +23,8 @@ public static IRfc3161TimestampRequest Create( throw new ArgumentNullException(nameof(messageHash)); } - IRfc3161TimestampRequest iRfc3161TimestampRequest = null; #if IS_DESKTOP - iRfc3161TimestampRequest = new Rfc3161TimestampRequestNet472Wrapper( + return new Rfc3161TimestampRequestNet472Wrapper( messageHash, hashAlgorithm, requestedPolicyId, @@ -33,7 +32,7 @@ public static IRfc3161TimestampRequest Create( requestSignerCertificates, extensions); #else - iRfc3161TimestampRequest = new Rfc3161TimestampRequestNetstandard21Wrapper( + return new Rfc3161TimestampRequestNetstandard21Wrapper( messageHash, hashAlgorithm, requestedPolicyId, @@ -41,8 +40,6 @@ public static IRfc3161TimestampRequest Create( requestSignerCertificates, extensions); #endif - return iRfc3161TimestampRequest; - } } } diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Verification/PackageSignatureVerifier.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Verification/PackageSignatureVerifier.cs index 9733de17e41..b3740648100 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Verification/PackageSignatureVerifier.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Verification/PackageSignatureVerifier.cs @@ -32,13 +32,13 @@ public PackageSignatureVerifier(IEnumerable veri throw new ArgumentNullException(nameof(settings)); } - var valid = false; var trustResults = new List(); var packageSigningTelemetryEvent = new PackageSigningTelemetryEvent(); using (var telemetry = TelemetryActivity.Create(parentId, packageSigningTelemetryEvent)) { var isSigned = await package.IsSignedAsync(token); + bool valid; if (isSigned) { try diff --git a/src/NuGet.Core/NuGet.ProjectModel/JsonPackageSpecReader.cs b/src/NuGet.Core/NuGet.ProjectModel/JsonPackageSpecReader.cs index 352e8083132..315f9d7d79a 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/JsonPackageSpecReader.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/JsonPackageSpecReader.cs @@ -1965,7 +1965,7 @@ private static void ReadTargetFrameworks(PackageSpec packageSpec, JsonTextReader [Obsolete] private static void AddTargetFramework(PackageSpec packageSpec, NuGetFramework frameworkName, NuGetFramework secondaryFramework, TargetFrameworkInformation targetFrameworkInformation) { - NuGetFramework updatedFramework = frameworkName; + NuGetFramework updatedFramework; if (targetFrameworkInformation.Imports.Length > 0) { diff --git a/src/NuGet.Core/NuGet.ProjectModel/ProjectLockFile/PackagesLockFileUtilities.cs b/src/NuGet.Core/NuGet.ProjectModel/ProjectLockFile/PackagesLockFileUtilities.cs index 5024109e92a..46fd2a1f32d 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/ProjectLockFile/PackagesLockFileUtilities.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/ProjectLockFile/PackagesLockFileUtilities.cs @@ -223,7 +223,7 @@ public static LockFileValidationResult IsLockFileValid(DependencyGraphSpec dgSpe if (p2pSpec != null) { - TargetFrameworkInformation p2pSpecTargetFrameworkInformation = default; + TargetFrameworkInformation p2pSpecTargetFrameworkInformation; if (p2pSpec.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig || p2pSpec.RestoreMetadata.ProjectStyle == ProjectStyle.Unknown) { // Skip compat check and dependency check for non PR projects. @@ -248,7 +248,7 @@ public static LockFileValidationResult IsLockFileValid(DependencyGraphSpec dgSpe if (hasChanged) { - // P2P transitive package dependencies have changed + // P2P transitive package dependencies have changed invalidReasons.Add(message); } diff --git a/src/NuGet.Core/NuGet.Protocol/LegacyFeed/ODataServiceDocumentResourceV2Provider.cs b/src/NuGet.Core/NuGet.Protocol/LegacyFeed/ODataServiceDocumentResourceV2Provider.cs index ec94fce03a8..3061a19b9b3 100644 --- a/src/NuGet.Core/NuGet.Protocol/LegacyFeed/ODataServiceDocumentResourceV2Provider.cs +++ b/src/NuGet.Core/NuGet.Protocol/LegacyFeed/ODataServiceDocumentResourceV2Provider.cs @@ -33,14 +33,13 @@ public ODataServiceDocumentResourceV2Provider() public override async Task> TryCreate(SourceRepository source, CancellationToken token) { ODataServiceDocumentResourceV2 serviceDocument = null; - ODataServiceDocumentCacheInfo cacheInfo = null; var url = source.PackageSource.Source; var utcNow = DateTime.UtcNow; var entryValidCutoff = utcNow.Subtract(MaxCacheDuration); // check the cache before downloading the file - if (!_cache.TryGetValue(url, out cacheInfo) || entryValidCutoff > cacheInfo.CachedTime) + if (!_cache.TryGetValue(url, out var cacheInfo) || entryValidCutoff > cacheInfo.CachedTime) { // Track if the semaphore needs to be released var release = false; diff --git a/src/NuGet.Core/NuGet.Protocol/PackagesFolder/LocalPackageFileCache.cs b/src/NuGet.Core/NuGet.Protocol/PackagesFolder/LocalPackageFileCache.cs index 7b32322b7db..73a17111ff9 100644 --- a/src/NuGet.Core/NuGet.Protocol/PackagesFolder/LocalPackageFileCache.cs +++ b/src/NuGet.Core/NuGet.Protocol/PackagesFolder/LocalPackageFileCache.cs @@ -177,24 +177,16 @@ private static bool IsAllowedLibraryFile(string path) /// private static NuspecReader GetNuspec(string manifestPath, string expandedPath) { - NuspecReader nuspec = null; - // Verify that the nuspec has the correct name before opening it if (File.Exists(manifestPath)) { - nuspec = new NuspecReader(File.OpenRead(manifestPath)); - } - else - { - // Scan the folder for the nuspec - using (var folderReader = new PackageFolderReader(expandedPath)) - { - // This will throw if the nuspec is not found - nuspec = new NuspecReader(folderReader.GetNuspec()); - } + return new NuspecReader(File.OpenRead(manifestPath)); } - return nuspec; + // Scan the folder for the nuspec + using var folderReader = new PackageFolderReader(expandedPath); + // This will throw if the nuspec is not found + return new NuspecReader(folderReader.GetNuspec()); } /// diff --git a/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepositoryUtility.cs b/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepositoryUtility.cs index 1cc57c65c39..e70b9d4384b 100644 --- a/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepositoryUtility.cs +++ b/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepositoryUtility.cs @@ -16,13 +16,11 @@ public static LocalPackageSourceInfo GetPackage( string id, NuGetVersion version) { - LocalPackageInfo package = null; - for (var i = 0; i < repositories.Count; i++) { var repository = repositories[i]; - package = repository.FindPackage(id, version); + LocalPackageInfo package = repository.FindPackage(id, version); if (package != null) { diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs index ac5322fc384..1c8e338d20b 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs @@ -133,7 +133,7 @@ public async Task HandleResponseAsync( var requestPayload = MessageUtilities.DeserializePayload(request); var packageSource = GetPackageSource(requestPayload.PackageSourceRepository); - GetCredentialsResponse responsePayload = null; + GetCredentialsResponse responsePayload; if (packageSource.IsHttp && string.Equals( diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/MetadataResourceV3.cs b/src/NuGet.Core/NuGet.Protocol/Resources/MetadataResourceV3.cs index d2144ab73d1..a843a359c87 100644 --- a/src/NuGet.Core/NuGet.Protocol/Resources/MetadataResourceV3.cs +++ b/src/NuGet.Core/NuGet.Protocol/Resources/MetadataResourceV3.cs @@ -104,10 +104,8 @@ public override async Task> GetVersions( foreach (var catalogEntry in entries) { - NuGetVersion version = null; - if (catalogEntry["version"] != null - && NuGetVersion.TryParse(catalogEntry["version"].ToString(), out version)) + && NuGetVersion.TryParse(catalogEntry["version"].ToString(), out var version)) { if (includePrerelease || !version.IsPrerelease) { diff --git a/src/NuGet.Core/NuGet.Versioning/VersionRange.cs b/src/NuGet.Core/NuGet.Versioning/VersionRange.cs index 20164f89596..f69d3d791ca 100644 --- a/src/NuGet.Core/NuGet.Versioning/VersionRange.cs +++ b/src/NuGet.Core/NuGet.Versioning/VersionRange.cs @@ -167,10 +167,8 @@ public virtual string ToLegacyShortString() /// public string ToString(string? format, IFormatProvider? formatProvider) { - string? formattedString = null; - if (formatProvider == null - || !TryFormatter(format, formatProvider, out formattedString)) + || !TryFormatter(format, formatProvider, out var formattedString)) { formattedString = ToString(); } diff --git a/src/NuGet.Core/NuGet.Versioning/VersionRangeFactory.cs b/src/NuGet.Core/NuGet.Versioning/VersionRangeFactory.cs index 7eaadb8b385..abd4b5af382 100644 --- a/src/NuGet.Core/NuGet.Versioning/VersionRangeFactory.cs +++ b/src/NuGet.Core/NuGet.Versioning/VersionRangeFactory.cs @@ -133,9 +133,9 @@ public static bool TryParse(string value, bool allowFloating, [NotNullWhen(true) return true; } - string? minVersionString = null; + string? minVersionString; string? maxVersionString = null; - var isMinInclusive = false; + bool isMinInclusive; var isMaxInclusive = false; NuGetVersion? minVersion = null; NuGetVersion? maxVersion = null; diff --git a/test/NuGet.Clients.FuncTests/NuGet.CommandLine.FuncTest/Commands/PushCommandTest.cs b/test/NuGet.Clients.FuncTests/NuGet.CommandLine.FuncTest/Commands/PushCommandTest.cs index 4248a226c49..50d2266432e 100644 --- a/test/NuGet.Clients.FuncTests/NuGet.CommandLine.FuncTest/Commands/PushCommandTest.cs +++ b/test/NuGet.Clients.FuncTests/NuGet.CommandLine.FuncTest/Commands/PushCommandTest.cs @@ -204,9 +204,9 @@ public void PushCommand_Server_SkipDuplicate_IsSpecified_PushProceeds() var sourcePath2 = Util.CreateTestPackage("PackageB", "1.1.0", pathContext.WorkingDirectory); var outputPath2 = Path.Combine(pathContext.WorkingDirectory, "pushed2.nupkg"); - CommandRunnerResult result = null; - CommandRunnerResult result2 = null; - CommandRunnerResult result3 = null; + CommandRunnerResult result; + CommandRunnerResult result2; + CommandRunnerResult result3; using (var server = new MockServer()) { @@ -826,8 +826,8 @@ public void PushCommand_Server_Snupkg_ByFilename_SnupkgExists_Conflict_ServerMes //Create snupkg in test directory. WriteSnupkgFile(snupkgFullPath); - CommandRunnerResult result = null; - CommandRunnerResult result2 = null; + CommandRunnerResult result; + CommandRunnerResult result2; using (var server = CreateAndStartMockV3Server(pathContext.WorkingDirectory, out string sourceName)) { diff --git a/test/NuGet.Clients.Tests/NuGet.PackageManagement.UI.Test/ViewModels/PackageItemViewModelTests.cs b/test/NuGet.Clients.Tests/NuGet.PackageManagement.UI.Test/ViewModels/PackageItemViewModelTests.cs index bee46352992..3e46b116e2a 100644 --- a/test/NuGet.Clients.Tests/NuGet.PackageManagement.UI.Test/ViewModels/PackageItemViewModelTests.cs +++ b/test/NuGet.Clients.Tests/NuGet.PackageManagement.UI.Test/ViewModels/PackageItemViewModelTests.cs @@ -341,7 +341,6 @@ private static async Task GetFinalIconBitmapAsync(PackageItemViewM NuGetPackageFileService.AddIconToCache(packageIdentity, packageItemViewModel.IconUrl); } - BitmapSource result = packageItemViewModel.IconBitmap; var millisecondsToWait = 200000; while (!IconBitmapStatusUtility.GetIsCompleted(packageItemViewModel.BitmapStatus) && millisecondsToWait >= 0) { @@ -349,8 +348,7 @@ private static async Task GetFinalIconBitmapAsync(PackageItemViewM millisecondsToWait -= 250; } - result = packageItemViewModel.IconBitmap; - return result; + return packageItemViewModel.IconBitmap; } [Theory] diff --git a/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/UWPRestoreTests.cs b/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/UWPRestoreTests.cs index bd96626e72d..5863e97101c 100644 --- a/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/UWPRestoreTests.cs +++ b/test/NuGet.Core.FuncTests/NuGet.Commands.FuncTest/UWPRestoreTests.cs @@ -271,7 +271,7 @@ public async Task UWPRestore_BlankUWPApp() var lockFileFormat = new LockFileFormat(); var expectedStream = GetResource("NuGet.Commands.FuncTest.compiler.resources.uwpBlankAppV2.json"); - JObject expectedJson = null; + JObject expectedJson; using (var reader = new StreamReader(expectedStream)) { diff --git a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageBuilderTest.cs b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageBuilderTest.cs index bfce63d8cca..a365db216f8 100644 --- a/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageBuilderTest.cs +++ b/test/NuGet.Core.Tests/NuGet.Packaging.Test/PackageBuilderTest.cs @@ -3339,7 +3339,7 @@ private IPackageFile CreatePackageFileOnPath(string path, DateTime lastWriteTime private Stream GetManifestStream(Stream packageStream) { - Stream resultStream = null; + Stream resultStream; using (var archive = new ZipArchive(packageStream, ZipArchiveMode.Read, leaveOpen: true)) { diff --git a/test/NuGet.Core.Tests/NuGet.ProjectModel.Test/LockFileFormatTests.cs b/test/NuGet.Core.Tests/NuGet.ProjectModel.Test/LockFileFormatTests.cs index 42ea06716a9..1b8be8ab986 100644 --- a/test/NuGet.Core.Tests/NuGet.ProjectModel.Test/LockFileFormatTests.cs +++ b/test/NuGet.Core.Tests/NuGet.ProjectModel.Test/LockFileFormatTests.cs @@ -541,7 +541,7 @@ public void Render_LockFileWithTarget_WritesTarget() ""buildMultiTargeting"": { ""buildMultiTargeting/Microsoft.Extensions.ApiDescription.Server.props"": {}, ""buildMultiTargeting/Microsoft.Extensions.ApiDescription.Server.targets"": {} - } + } }, ""runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0"": { ""type"": ""package"", @@ -1396,10 +1396,9 @@ public void LockFileFormat_ReadsMinimalErrorMessage(IEnvironmentVariableReader e ] }"; LockFile lockFileObj = null; - IAssetsLogMessage logMessage = null; + IAssetsLogMessage logMessage; using (var lockFile = new TempFile()) { - File.WriteAllText(lockFile, lockFileContent); // Act @@ -1479,7 +1478,7 @@ private void LockFileFormat_ReadUsesReadFlags_WithEnvReader(LockFileReadFlags fl ""centralTransitiveDependencyGroups"": { "".NETPlatform,Version=v5.0"": { ""Newtonsoft.Json"": { - ""version"": ""1.0.0"" + ""version"": ""1.0.0"" } } }, @@ -1561,8 +1560,8 @@ public void LockFileFormat_SkipsInvalidErrorMessage(IEnvironmentVariableReader e } ] }"; - LockFile lockFileObj = null; - IAssetsLogMessage logMessage = null; + LockFile lockFileObj; + IAssetsLogMessage logMessage; using (var lockFile = new TempFile()) { @@ -2404,7 +2403,7 @@ public void LockFileFormat_WritesCentralTransitiveDependencyGroups() ""type"": ""package"", ""files"": [ ""System.Runtime.nuspec"" - ] + ] } }, ""projectFileDependencyGroups"": { @@ -2418,7 +2417,7 @@ public void LockFileFormat_WritesCentralTransitiveDependencyGroups() ""Newtonsoft.Json"": { ""include"": ""Compile, Native, BuildTransitive"", ""suppressParent"": ""All"", - ""version"": ""[12.0.3, )"" + ""version"": ""[12.0.3, )"" } } } diff --git a/test/NuGet.Core.Tests/NuGet.Versioning.Test/SemVer201SpecTests.cs b/test/NuGet.Core.Tests/NuGet.Versioning.Test/SemVer201SpecTests.cs index 3f968284d63..f8ac7d053f1 100644 --- a/test/NuGet.Core.Tests/NuGet.Versioning.Test/SemVer201SpecTests.cs +++ b/test/NuGet.Core.Tests/NuGet.Versioning.Test/SemVer201SpecTests.cs @@ -310,9 +310,8 @@ public void SemVerSortReleaseAlpha(string lower, string higher) public void SemVerSortNumericAlpha(string lower, string higher) { // Arrange & act - SemanticVersion? lowerSemVer = null, higherSemVer = null; - SemanticVersion.TryParse(lower, out lowerSemVer); - SemanticVersion.TryParse(higher, out higherSemVer); + SemanticVersion.TryParse(lower, out var lowerSemVer); + SemanticVersion.TryParse(higher, out var higherSemVer); // Assert Assert.True(VersionComparer.Default.Compare(lowerSemVer!, higherSemVer!) < 0); @@ -325,9 +324,8 @@ public void SemVerSortNumericAlpha(string lower, string higher) public void SemVerSortReleaseLabelCount(string lower, string higher) { // Arrange & act - SemanticVersion? lowerSemVer = null, higherSemVer = null; - SemanticVersion.TryParse(lower, out lowerSemVer); - SemanticVersion.TryParse(higher, out higherSemVer); + SemanticVersion.TryParse(lower, out var lowerSemVer); + SemanticVersion.TryParse(higher, out var higherSemVer); // Assert Assert.True(VersionComparer.Default.Compare(lowerSemVer!, higherSemVer!) < 0); @@ -340,9 +338,8 @@ public void SemVerSortReleaseLabelCount(string lower, string higher) public void SemVerSortIgnoreReleaseCasing(string a, string b) { // Arrange & act - SemanticVersion? semVerA = null, semVerB = null; - SemanticVersion.TryParse(a, out semVerA); - SemanticVersion.TryParse(b, out semVerB); + SemanticVersion.TryParse(a, out var semVerA); + SemanticVersion.TryParse(b, out var semVerB); // Assert Assert.True(VersionComparer.Default.Equals(semVerA!, semVerB!));