diff --git a/build/Shared/EqualityUtility.cs b/build/Shared/EqualityUtility.cs index dc06c317b35..bb94d78ed42 100644 --- a/build/Shared/EqualityUtility.cs +++ b/build/Shared/EqualityUtility.cs @@ -28,8 +28,7 @@ internal static bool OrderedEquals(this IEnumerable? sel Debug.Assert(orderComparer != null || typeof(TKey) != typeof(string), "Argument " + "orderComparer" + " must be provided if " + "TKey" + " is a string."); Debug.Assert(sequenceComparer != null || typeof(TSource) != typeof(string), "Argument " + "sequenceComparer" + " must be provided if " + "TSource" + " is a string."); - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -54,8 +53,7 @@ internal static bool OrderedEquals(this ICollection? sel Debug.Assert(orderComparer != null || typeof(TKey) != typeof(string), "Argument " + "orderComparer" + " must be provided if " + "TKey" + " is a string."); Debug.Assert(sequenceComparer != null || typeof(TSource) != typeof(string), "Argument " + "sequenceComparer" + " must be provided if " + "TSource" + " is a string."); - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -96,8 +94,7 @@ internal static bool OrderedEquals(this IList? self, ILi Debug.Assert(orderComparer != null || typeof(TKey) != typeof(string), "Argument " + "orderComparer" + " must be provided if " + "TKey" + " is a string."); Debug.Assert(sequenceComparer != null || typeof(TSource) != typeof(string), "Argument " + "sequenceComparer" + " must be provided if " + "TSource" + " is a string."); - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -131,8 +128,7 @@ internal static bool SequenceEqualWithNullCheck( IEnumerable? other, IEqualityComparer? comparer = null) { - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -154,8 +150,7 @@ internal static bool SequenceEqualWithNullCheck( ICollection? other, IEqualityComparer? comparer = null) { - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -187,8 +182,7 @@ internal static bool SequenceEqualWithNullCheck( IList? other, IEqualityComparer? comparer = null) { - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -225,8 +219,7 @@ internal static bool SetEqualsWithNullCheck( ISet? other, IEqualityComparer? comparer = null) { - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -262,8 +255,7 @@ internal static bool DictionaryEquals( Func comparerFunc = (s, o) => comparer.Equals(s, o); compareValues = compareValues ?? comparerFunc; - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } @@ -312,8 +304,7 @@ internal static bool DictionaryOfSequenceEquals( internal static bool EqualsWithNullCheck(T self, T other) { - bool identityEquals; - if (TryIdentityEquals(self, other, out identityEquals)) + if (TryIdentityEquals(self, other, out var identityEquals)) { return identityEquals; } diff --git a/src/NuGet.Clients/NuGet.CommandLine/Commands/PackCommand.cs b/src/NuGet.Clients/NuGet.CommandLine/Commands/PackCommand.cs index dcf7a55264b..5197b610338 100644 --- a/src/NuGet.Clients/NuGet.CommandLine/Commands/PackCommand.cs +++ b/src/NuGet.Clients/NuGet.CommandLine/Commands/PackCommand.cs @@ -177,8 +177,7 @@ public override void ExecuteCommand() if (!string.IsNullOrEmpty(Version)) { - NuGetVersion version; - if (!NuGetVersion.TryParse(Version, out version)) + if (!NuGetVersion.TryParse(Version, out var version)) { throw new PackagingException(NuGetLogCode.NU5010, string.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandPackageReferenceInvalidVersion, Version)); } diff --git a/src/NuGet.Clients/NuGet.CommandLine/Commands/ProjectFactory.cs b/src/NuGet.Clients/NuGet.CommandLine/Commands/ProjectFactory.cs index 75907b4a978..dea91a67799 100644 --- a/src/NuGet.Clients/NuGet.CommandLine/Commands/ProjectFactory.cs +++ b/src/NuGet.Clients/NuGet.CommandLine/Commands/ProjectFactory.cs @@ -432,8 +432,7 @@ public string InitializeProperties(Packaging.IPackageMetadata metadata) public string GetPropertyValue(string propertyName) { - string value; - if (!_properties.TryGetValue(propertyName, out value) && + if (!_properties.TryGetValue(propertyName, out var value) && !ProjectProperties.TryGetValue(propertyName, out value)) { dynamic property = _project.GetProperty(propertyName); @@ -555,9 +554,7 @@ private void ExtractMetadataFromProject(Packaging.PackageBuilder builder) string version = _project.GetPropertyValue("Version"); if (builder.Version == null) { - NuGetVersion parsedVersion; - - if (NuGetVersion.TryParse(version, out parsedVersion)) + if (NuGetVersion.TryParse(version, out var parsedVersion)) { builder.Version = parsedVersion; } @@ -658,8 +655,7 @@ private static bool ShouldExcludeItem(dynamic item) if (item.HasMetadata(ReferenceOutputAssembly)) { - bool result; - if (bool.TryParse(item.GetMetadataValue("ReferenceOutputAssembly"), out result)) + if (bool.TryParse(item.GetMetadataValue("ReferenceOutputAssembly"), out bool result)) { if (!result) { @@ -1172,8 +1168,7 @@ private static void ProcessTransformFiles(PackageBuilder builder, IEnumerable(behaviorStr, ignoreCase: true, result: out dependencyBehavior) || + if (!Enum.TryParse(behaviorStr, ignoreCase: true, result: out var dependencyBehavior) || !Enum.IsDefined(typeof(DependencyBehavior), dependencyBehavior)) { throw new CommandException(string.Format(CultureInfo.CurrentCulture, diff --git a/src/NuGet.Clients/NuGet.CommandLine/Common/ResourceHelper.cs b/src/NuGet.Clients/NuGet.CommandLine/Common/ResourceHelper.cs index 39bafe2495a..abd3f28db32 100644 --- a/src/NuGet.Clients/NuGet.CommandLine/Common/ResourceHelper.cs +++ b/src/NuGet.Clients/NuGet.CommandLine/Common/ResourceHelper.cs @@ -30,8 +30,7 @@ public static string GetLocalizedString(Type resourceType, string resourceNames) _cachedManagers = new Dictionary(); } - ResourceManager resourceManager; - if (!_cachedManagers.TryGetValue(resourceType, out resourceManager)) + if (!_cachedManagers.TryGetValue(resourceType, out var resourceManager)) { PropertyInfo property = resourceType.GetProperty("ResourceManager", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); diff --git a/src/NuGet.Clients/NuGet.CommandLine/MsBuildToolset.cs b/src/NuGet.Clients/NuGet.CommandLine/MsBuildToolset.cs index 92041cd0204..ecbb2f443ed 100644 --- a/src/NuGet.Clients/NuGet.CommandLine/MsBuildToolset.cs +++ b/src/NuGet.Clients/NuGet.CommandLine/MsBuildToolset.cs @@ -134,8 +134,7 @@ public static string GetMsBuildDirFromVsDir(string vsDir) private static float ToFloatValue(string directoryName) { var dirName = new DirectoryInfo(directoryName).Name; - float dirValue; - if (float.TryParse(dirName, NumberStyles.Float, CultureInfo.InvariantCulture, out dirValue)) + if (float.TryParse(dirName, NumberStyles.Float, CultureInfo.InvariantCulture, out var dirValue)) { return dirValue; } diff --git a/src/NuGet.Clients/NuGet.CommandLine/MsBuildUtility.cs b/src/NuGet.Clients/NuGet.CommandLine/MsBuildUtility.cs index 39e84ee714f..65cbb579b74 100644 --- a/src/NuGet.Clients/NuGet.CommandLine/MsBuildUtility.cs +++ b/src/NuGet.Clients/NuGet.CommandLine/MsBuildUtility.cs @@ -809,10 +809,8 @@ private static MsBuildToolset GetToolsetFromUserVersion( // without the safe fallback to 0.0 built into t.ParsedToolsVersion. selectedToolset = installedToolsets.FirstOrDefault(t => { - Version parsedUserVersion; - Version parsedToolsVersion; - if (Version.TryParse(userVersionString, out parsedUserVersion) && - Version.TryParse(t.Version, out parsedToolsVersion)) + if (Version.TryParse(userVersionString, out var parsedUserVersion) && + Version.TryParse(t.Version, out var parsedToolsVersion)) { return parsedToolsVersion.Major == parsedUserVersion.Major && parsedToolsVersion.Minor == parsedUserVersion.Minor; @@ -945,8 +943,7 @@ private static List GetInstalledSxsToolsets() while (true) { var fetchedInstances = new ISetupInstance[3]; - int fetched; - enumerator.Next(fetchedInstances.Length, fetchedInstances, out fetched); + enumerator.Next(fetchedInstances.Length, fetchedInstances, out var fetched); if (fetched == 0) { break; diff --git a/src/NuGet.Clients/NuGet.CommandLine/SettingsCredentialProvider.cs b/src/NuGet.Clients/NuGet.CommandLine/SettingsCredentialProvider.cs index b46d21ebe95..9d56560ebe2 100644 --- a/src/NuGet.Clients/NuGet.CommandLine/SettingsCredentialProvider.cs +++ b/src/NuGet.Clients/NuGet.CommandLine/SettingsCredentialProvider.cs @@ -47,11 +47,10 @@ private bool TryGetCredentials(Uri uri, out ICredentials configurationCredential { var source = _packageSourceProvider.LoadPackageSources().FirstOrDefault(p => { - Uri sourceUri; return p.Credentials != null - && p.Credentials.IsValid() - && Uri.TryCreate(p.Source, UriKind.Absolute, out sourceUri) - && UriEquals(sourceUri, uri); + && p.Credentials.IsValid() + && Uri.TryCreate(p.Source, UriKind.Absolute, out var sourceUri) + && UriEquals(sourceUri, uri); }); if (source == null) { diff --git a/src/NuGet.Clients/NuGet.Console/Console/TextFormatClassifier.cs b/src/NuGet.Clients/NuGet.Console/Console/TextFormatClassifier.cs index 56001a07afa..0479bd4cb63 100644 --- a/src/NuGet.Clients/NuGet.Console/Console/TextFormatClassifier.cs +++ b/src/NuGet.Clients/NuGet.Console/Console/TextFormatClassifier.cs @@ -91,8 +91,7 @@ private static TextFormattingRunProperties GetFormat(Color? foreground, Color? b public IClassificationType GetClassificationType(Color? foreground, Color? background) { var key = Tuple.Create(foreground, background); - IClassificationType classificationType; - if (!_classificationMap.TryGetValue(key, out classificationType)) + if (!_classificationMap.TryGetValue(key, out var classificationType)) { string classificationName = GetClassificationName(foreground, background); classificationType = Factory.ClassificationTypeRegistryService.GetClassificationType(classificationName); diff --git a/src/NuGet.Clients/NuGet.Console/OutputConsole/OutputConsole.cs b/src/NuGet.Clients/NuGet.Console/OutputConsole/OutputConsole.cs index 868ef93c905..4961a2be3ad 100644 --- a/src/NuGet.Clients/NuGet.Console/OutputConsole/OutputConsole.cs +++ b/src/NuGet.Clients/NuGet.Console/OutputConsole/OutputConsole.cs @@ -55,10 +55,9 @@ public OutputConsole( fClearWithSolution: 0); ErrorHandler.ThrowOnFailure(hr); - IVsOutputWindowPane pane; hr = _vsOutputWindow.GetPane( ref outputWindowPaneId, - out pane); + out var pane); ErrorHandler.ThrowOnFailure(hr); GuidList.NuGetOutputWindowPaneGuid = outputWindowPaneId; diff --git a/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsole.cs b/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsole.cs index 41073ea6c2d..474aeab9ca4 100644 --- a/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsole.cs +++ b/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsole.cs @@ -173,9 +173,8 @@ private IWpfTextViewHost WpfTextViewHost get { var userData = VsTextView as IVsUserData; - object data; Guid guidIWpfTextViewHost = EditorDefGuidList.guidIWpfTextViewHost; - userData.GetData(ref guidIWpfTextViewHost, out data); + userData.GetData(ref guidIWpfTextViewHost, out var data); var wpfTextViewHost = data as IWpfTextViewHost; return wpfTextViewHost; @@ -320,9 +319,8 @@ public IVsTextView VsTextView var propCategoryContainer = _view as IVsTextEditorPropertyCategoryContainer; if (propCategoryContainer != null) { - IVsTextEditorPropertyContainer propContainer; Guid guidPropCategory = EditorDefGuidList.guidEditPropCategoryViewMasterSettings; - int hr = propCategoryContainer.GetPropertyCategory(ref guidPropCategory, out propContainer); + int hr = propCategoryContainer.GetPropertyCategory(ref guidPropCategory, out var propContainer); if (hr == 0) { propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_FontCategory, diff --git a/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleClassifier.cs b/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleClassifier.cs index bed99b2b154..49183d34480 100644 --- a/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleClassifier.cs +++ b/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleClassifier.cs @@ -207,8 +207,7 @@ public IList GetClassificationSpans(SnapshotSpan span) /// private IList GetCommandLineClassifications(ITextSnapshot snapshot, IList cmdSpans) { - IList cachedCommandLineClassifications; - if (TryGetCachedCommandLineClassifications(snapshot, cmdSpans, out cachedCommandLineClassifications)) + if (TryGetCachedCommandLineClassifications(snapshot, cmdSpans, out var cachedCommandLineClassifications)) { return cachedCommandLineClassifications; } diff --git a/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleCompletionSource.cs b/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleCompletionSource.cs index 83d6ec5251a..7af435136c2 100644 --- a/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleCompletionSource.cs +++ b/src/NuGet.Clients/NuGet.Console/WpfConsole/WpfConsoleCompletionSource.cs @@ -44,8 +44,7 @@ public void AugmentCompletionSession(ICompletionSession session, IList completions = new List(); foreach (string s in simpleExpansion.Expansions) diff --git a/src/NuGet.Clients/NuGet.Indexing/NuGetQuery.cs b/src/NuGet.Clients/NuGet.Indexing/NuGetQuery.cs index b26f0b120b2..203eb178a60 100644 --- a/src/NuGet.Clients/NuGet.Indexing/NuGetQuery.cs +++ b/src/NuGet.Clients/NuGet.Indexing/NuGetQuery.cs @@ -18,8 +18,7 @@ public static Query MakeQuery(string q) var grouping = new Dictionary>(); foreach (Clause clause in MakeClauses(Tokenize(q))) { - HashSet text; - if (!grouping.TryGetValue(clause.Field, out text)) + if (!grouping.TryGetValue(clause.Field, out var text)) { text = new HashSet(); grouping.Add(clause.Field, text); diff --git a/src/NuGet.Clients/NuGet.Indexing/SearchResultsAggregator.cs b/src/NuGet.Clients/NuGet.Indexing/SearchResultsAggregator.cs index 203b49cffef..ad9d3c0326c 100644 --- a/src/NuGet.Clients/NuGet.Indexing/SearchResultsAggregator.cs +++ b/src/NuGet.Clients/NuGet.Indexing/SearchResultsAggregator.cs @@ -114,8 +114,7 @@ public void MergeResults(IEnumerable result) { foreach (var entry in result) { - IPackageSearchMetadata value; - if (_index.TryGetValue(entry.Identity.Id, out value)) + if (_index.TryGetValue(entry.Identity.Id, out var value)) { _index[entry.Identity.Id] = _splicer.MergeEntries(value, entry); } diff --git a/src/NuGet.Clients/NuGet.Indexing/SemanticVersionFilter.cs b/src/NuGet.Clients/NuGet.Indexing/SemanticVersionFilter.cs index 705e0817f07..8af80c15d51 100644 --- a/src/NuGet.Clients/NuGet.Indexing/SemanticVersionFilter.cs +++ b/src/NuGet.Clients/NuGet.Indexing/SemanticVersionFilter.cs @@ -25,8 +25,7 @@ public override bool IncrementToken() string version = _termAttribute.Term; - NuGetVersion nuGetVersion; - if (NuGetVersion.TryParse(version, out nuGetVersion)) + if (NuGetVersion.TryParse(version, out var nuGetVersion)) { version = nuGetVersion.ToNormalizedString(); } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Model/PowerShellPackage.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Model/PowerShellPackage.cs index 3b79e4df8ee..1975ce59f83 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Model/PowerShellPackage.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Model/PowerShellPackage.cs @@ -52,8 +52,7 @@ public NuGet.SemanticVersion Version if (nVersion != null) { - NuGet.SemanticVersion sVersion; - _ = NuGet.SemanticVersion.TryParse(nVersion.ToNormalizedString(), out sVersion); + _ = NuGet.SemanticVersion.TryParse(nVersion.ToNormalizedString(), out var sVersion); return sVersion; } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs index 6b7fe93cd31..5fc8a681af3 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/NuGetPowerShellBaseCommand.cs @@ -419,10 +419,8 @@ private SourceValidationResult CheckSourceValidity(string inputSource) Uri sourceUri; if (Uri.TryCreate(source, UriKind.Relative, out sourceUri)) { - string outputPath; - bool? exists; string errorMessage; - if (PSPathUtility.TryTranslatePSPath(SessionState, source, out outputPath, out exists, out errorMessage) && + if (PSPathUtility.TryTranslatePSPath(SessionState, source, out var outputPath, out var exists, out errorMessage) && exists == true) { source = outputPath; diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs index aa183c2f97d..bda1916d6e2 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PackageActionBaseCommand.cs @@ -383,8 +383,7 @@ protected virtual DependencyBehavior GetDependencyBehavior() protected DependencyBehavior GetDependencyBehaviorFromConfig() { var dependencySetting = SettingsUtility.GetConfigValue(ConfigSettings, ConfigurationConstants.DependencyVersion); - DependencyBehavior behavior; - var success = Enum.TryParse(dependencySetting, ignoreCase: true, result: out behavior); + var success = Enum.TryParse(dependencySetting, ignoreCase: true, result: out DependencyBehavior behavior); if (success) { return behavior; diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PowerShellHost.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PowerShellHost.cs index 514b511328a..fe7f7ef17ac 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PowerShellHost.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/PowerShellHost.cs @@ -207,8 +207,7 @@ private ComplexCommand ComplexCommand { _complexCommand = new ComplexCommand((allLines, lastLine) => { - Collection errors; - PSParser.Tokenize(allLines, out errors); + PSParser.Tokenize(allLines, out var errors); // If there is a parse error token whose END is past input END, consider // it a multi-line command. @@ -569,8 +568,7 @@ public bool Execute(IConsole console, string command, params object[] inputs) ActiveConsole = console; - string fullCommand; - if (ComplexCommand.AddLine(command, out fullCommand) + if (ComplexCommand.AddLine(command, out var fullCommand) && !string.IsNullOrEmpty(fullCommand)) { // create a new token source with each command since CTS aren't usable once cancelled. diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PSPathUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PSPathUtility.cs index b4053afe303..cdbb17d9062 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PSPathUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PSPathUtility.cs @@ -62,11 +62,10 @@ public static bool TryTranslatePSPath(SessionState session, string psPath, out s // we do not glob wildcards (literalpath.) exists = session.InvokeProvider.Item.Exists(psPath, force: false, literalPath: true); - ProviderInfo provider; PSDriveInfo drive; // translate pspath, not trying to glob. - path = session.Path.GetUnresolvedProviderPathFromPSPath(psPath, out provider, out drive); + path = session.Path.GetUnresolvedProviderPathFromPSPath(psPath, out var provider, out drive); // ensure path is on the filesystem (not registry, certificate, variable etc.) if (provider.ImplementingType != typeof(FileSystemProvider)) diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PowerShellCmdletsUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PowerShellCmdletsUtility.cs index 617f44dbc73..3f8b367f1ae 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PowerShellCmdletsUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utility/PowerShellCmdletsUtility.cs @@ -22,8 +22,7 @@ public static NuGetVersion GetNuGetVersionFromString(string version) throw new ArgumentNullException(nameof(version)); } - NuGetVersion nVersion; - var success = NuGetVersion.TryParse(version, out nVersion); + var success = NuGetVersion.TryParse(version, out var nVersion); if (!success) { throw new InvalidOperationException( diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/InstalledPackageEnumerator.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/InstalledPackageEnumerator.cs index d5e2c400a85..c18f3e4af93 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/InstalledPackageEnumerator.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/InstalledPackageEnumerator.cs @@ -170,8 +170,7 @@ private async Task ProcessPackagesConfigProjectsAsync( { var result = await CollectPackagesForPackagesConfigAsync(project, token); - ISet frameworkPackages; - if (!packagesByFramework.TryGetValue(result.Item1, out frameworkPackages)) + if (!packagesByFramework.TryGetValue(result.Item1, out var frameworkPackages)) { frameworkPackages = new HashSet(); packagesByFramework.Add(result.Item1, frameworkPackages); @@ -203,8 +202,7 @@ private async Task>> CollectP if (installedRefs?.Any() == true) { // Index packages.config references by target framework since this affects dependencies - NuGetFramework targetFramework; - if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out targetFramework)) + if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out NuGetFramework targetFramework)) { targetFramework = NuGetFramework.AnyFramework; } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/MethodBinder.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/MethodBinder.cs index 83b530620ce..0b1837a30ea 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/MethodBinder.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/MethodBinder.cs @@ -181,9 +181,8 @@ private object[] UnwrapArgs(MethodInfo m, object[] args) for (int i = 0; i < paramInfos.Length; i++) { ParameterInfo paramInfo = paramInfos[i]; - object argValue; if (k < args.Length - && TryConvertArg(paramInfo, args[k], out argValue)) // If args[k] matches + && TryConvertArg(paramInfo, args[k], out var argValue)) // If args[k] matches { newArgs[i] = argValue; k++; diff --git a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/TypeWrapper.cs b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/TypeWrapper.cs index 0d0c322b4c9..ba6fffd3824 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/TypeWrapper.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/Utils/TypeWrapper.cs @@ -79,8 +79,7 @@ protected T GetInterface(Type interfaceType) lock (_interfaceMapLock) { - T interfaceWrapper; - if (_interfaceMap.TryGetValue(interfaceType, out interfaceWrapper)) + if (_interfaceMap.TryGetValue(interfaceType, out var interfaceWrapper)) { return interfaceWrapper; } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Common/ErrorFloodGate.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Common/ErrorFloodGate.cs index 558b4fcf2bc..e6c14b4cdcf 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Common/ErrorFloodGate.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Common/ErrorFloodGate.cs @@ -48,8 +48,7 @@ private static void ExpireOlderValues(ConcurrentQueue q, int expirationOffs { while (q.Count > 0) { - int result; - bool peekSucceeded = q.TryPeek(out result); + bool peekSucceeded = q.TryPeek(out var result); if (!peekSucceeded) { continue; diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/DataStreamFromComStream.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/DataStreamFromComStream.cs index 12f35d6a378..6cb9287cd6a 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/DataStreamFromComStream.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/DataStreamFromComStream.cs @@ -81,7 +81,6 @@ public override long Position public override int Read(byte[] buffer, int offset, int count) { ThreadHelper.ThrowIfNotOnUIThread(); - uint bytesRead = 0; byte[] b = buffer; if (offset != 0) @@ -90,7 +89,7 @@ public override int Read(byte[] buffer, int offset, int count) Array.Copy(buffer, offset, b, 0, buffer.Length - offset); } - _comStream.Read(b, (uint)count, out bytesRead); + _comStream.Read(b, (uint)count, out var bytesRead); if (offset != 0) { @@ -122,7 +121,6 @@ public override void SetLength(long value) public override void Write(byte[] buffer, int offset, int count) { ThreadHelper.ThrowIfNotOnUIThread(); - uint bytesWritten; if (count > 0) { byte[] b = buffer; @@ -132,7 +130,7 @@ public override void Write(byte[] buffer, int offset, int count) Array.Copy(buffer, offset, b, 0, buffer.Length - offset); } - _comStream.Write(b, (uint)count, out bytesWritten); + _comStream.Write(b, (uint)count, out var bytesWritten); if (bytesWritten != count) { throw new IOException(); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/SolutionUserOptions.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/SolutionUserOptions.cs index ec63b1933ff..0bd4b789ba5 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/SolutionUserOptions.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/UserInterfaceService/SolutionUserOptions.cs @@ -35,8 +35,7 @@ public SolutionUserOptions( public UserSettings GetSettings(string key) { - UserSettings settings; - if (_settings.WindowSettings.TryGetValue(key, out settings)) + if (_settings.WindowSettings.TryGetValue(key, out var settings)) { return settings ?? new UserSettings(); } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Utility/VsUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Utility/VsUtility.cs index c3779d91e37..46eeedc49f7 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Utility/VsUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Utility/VsUtility.cs @@ -11,16 +11,14 @@ public static IEnumerable GetDocumentWindows(IVsUIShell uiShell) { ThreadHelper.ThrowIfNotOnUIThread(); - IEnumWindowFrames documentWindowEnumerator; - var hr = uiShell.GetDocumentWindowEnum(out documentWindowEnumerator); + var hr = uiShell.GetDocumentWindowEnum(out var documentWindowEnumerator); if (documentWindowEnumerator == null) { yield break; } var windowFrames = new IVsWindowFrame[1]; - uint frameCount; - while (documentWindowEnumerator.Next(1, windowFrames, out frameCount) == VSConstants.S_OK && + while (documentWindowEnumerator.Next(1, windowFrames, out var frameCount) == VSConstants.S_OK && frameCount == 1) { yield return windowFrames[0]; @@ -32,10 +30,9 @@ public static PackageManagerControl GetPackageManagerControl(IVsWindowFrame wind { ThreadHelper.ThrowIfNotOnUIThread(); - object property; var hr = windowFrame.GetProperty( (int)__VSFPROPID.VSFPROPID_DocView, - out property); + out var property); var windowPane = property as PackageManagerWindowPane; if (windowPane == null) diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs index 610c47c781a..8b59ce5c863 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/PackageManagerControl.xaml.cs @@ -513,8 +513,7 @@ private static bool IsUILegalDisclaimerSuppressed() var configSection = nugetSettings.GetSection(ConfigurationConstants.Config); var dependencySetting = configSection?.GetFirstItemWithAttribute(ConfigurationConstants.KeyAttribute, ConfigurationConstants.DependencyVersion); - DependencyBehavior behavior; - var success = Enum.TryParse(dependencySetting?.Value, ignoreCase: true, result: out behavior); + var success = Enum.TryParse(dependencySetting?.Value, ignoreCase: true, result: out DependencyBehavior behavior); if (success) { return behavior; diff --git a/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/ProjectView.xaml.cs b/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/ProjectView.xaml.cs index c9d54109183..d4550579406 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/ProjectView.xaml.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.UI/Xamls/ProjectView.xaml.cs @@ -251,10 +251,9 @@ private void Versions_KeyUp(object sender, KeyEventArgs e) private void SetComboboxCurrentVersion(string comboboxText, IEnumerable versions) { NuGetVersion matchVersion = null; - VersionRange userRange = null; // Get the best version from the range if the user typed a custom version - bool userTypedAValidVersionRange = VersionRange.TryParse(comboboxText, out userRange); + bool userTypedAValidVersionRange = VersionRange.TryParse(comboboxText, out var userRange); if (userTypedAValidVersionRange) { matchVersion = userRange.FindBestMatch(versions); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/IDE/VSSolutionManager.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/IDE/VSSolutionManager.cs index ebb4e8a22d3..67d98fd2c76 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/IDE/VSSolutionManager.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/IDE/VSSolutionManager.cs @@ -330,8 +330,7 @@ public async Task IsAllProjectsNominatedAsync() foreach (var project in netCoreProjects) { // check if this .Net core project is nominated or not. - DependencyGraphSpec projectRestoreInfo; - if (!_projectSystemCache.TryGetProjectRestoreInfo(project.MSBuildProjectPath, out projectRestoreInfo, nominationMessages: out _) || + if (!_projectSystemCache.TryGetProjectRestoreInfo(project.MSBuildProjectPath, out var projectRestoreInfo, nominationMessages: out _) || projectRestoreInfo == null) { // there are projects still to be nominated. @@ -682,8 +681,7 @@ private void OnEnvDTEProjectRemoved(EnvDTE.Project envDTEProject) // This is a solution event. Should be on the UI thread ThreadHelper.ThrowIfNotOnUIThread(); - NuGetProject nuGetProject; - _projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out nuGetProject); + _projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out var nuGetProject); RemoveVsProjectAdapterFromCache(envDTEProject.FullName); @@ -704,8 +702,7 @@ private void OnEnvDTEProjectAdded(Project envDTEProject) await EnsureNuGetAndVsProjectAdapterCacheAsync(); var vsProjectAdapter = await _vsProjectAdapterProvider.CreateAdapterForFullyLoadedProjectAsync(envDTEProject); await AddVsProjectAdapterToCacheAsync(vsProjectAdapter); - NuGetProject nuGetProject; - _projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out nuGetProject); + _projectSystemCache.TryGetNuGetProject(envDTEProject.Name, out var nuGetProject); NuGetProjectAdded?.Invoke(this, new NuGetProjectEventArgs(nuGetProject)); } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsCoreProjectSystemReferenceReader.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsCoreProjectSystemReferenceReader.cs index 9d55e8ce902..b868ff23680 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsCoreProjectSystemReferenceReader.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsCoreProjectSystemReferenceReader.cs @@ -196,27 +196,24 @@ private IList GetExcludedReferences( var hierarchy = _vsProjectAdapter.VsHierarchy; // Get all items in the hierarchy, this includes project references, files, and everything else. - IEnumHierarchyItems items; if (ErrorHandler.Succeeded(itemsFactory.EnumHierarchyItems( - hierarchy, - (uint)__VSEHI.VSEHI_Leaf, - (uint)VSConstants.VSITEMID.Root, - out items))) + hierarchy, + (uint)__VSEHI.VSEHI_Leaf, + (uint)VSConstants.VSITEMID.Root, + out var items))) { var buildPropertyStorage = (IVsBuildPropertyStorage)hierarchy; // Loop through all items - uint fetched; var item = new VSITEMSELECTION[1]; - while (ErrorHandler.Succeeded(items.Next(1, item, out fetched)) && fetched == 1) + while (ErrorHandler.Succeeded(items.Next(1, item, out var fetched)) && fetched == 1) { // Check if the item has ReferenceOutputAssembly. This will // return null for the vast majority of items. - string value; if (ErrorHandler.Succeeded(buildPropertyStorage.GetItemAttribute( item[0].itemid, "ReferenceOutputAssembly", - out value)) + out var value)) && value != null) { // We only need to go farther if the flag exists and is not true @@ -224,11 +221,10 @@ private IList GetExcludedReferences( { // Get the DTE Project reference for the item id. This checks for nulls incase this is // somehow not a project reference that had the ReferenceOutputAssembly flag. - object childObject; if (ErrorHandler.Succeeded(hierarchy.GetProperty( - item[0].itemid, - (int)__VSHPROPID.VSHPROPID_ExtObject, - out childObject))) + item[0].itemid, + (int)__VSHPROPID.VSHPROPID_ExtObject, + out var childObject))) { // 1. Verify that this is a project reference // 2. Check that it is valid and resolved diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsManagedLanguagesProjectSystemServices.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsManagedLanguagesProjectSystemServices.cs index bd4ee993f93..488b84a57be 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsManagedLanguagesProjectSystemServices.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/ProjectServices/VsManagedLanguagesProjectSystemServices.cs @@ -152,9 +152,7 @@ public async Task> GetProjectReferencesAsyn { if (r.SourceProject != null && await EnvDTEProjectUtility.IsSupportedAsync(r.SourceProject)) { - Array metadataElements; - Array metadataValues; - r.GetMetadata(ReferenceMetadata, out metadataElements, out metadataValues); + r.GetMetadata(ReferenceMetadata, out var metadataElements, out var metadataValues); references.Add(ToProjectRestoreReference(new ProjectReference( uniqueName: r.SourceProject.FullName, diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/CpsPackageReferenceProject.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/CpsPackageReferenceProject.cs index 421d64415b9..acc54dbebeb 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/CpsPackageReferenceProject.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/CpsPackageReferenceProject.cs @@ -101,8 +101,7 @@ protected override Task GetAssetsFilePathAsync(bool shouldThrow) private PackageSpec GetPackageSpec() { - DependencyGraphSpec projectRestoreInfo; - if (_projectSystemCache.TryGetProjectRestoreInfo(ProjectFullPath, out projectRestoreInfo, out _)) + if (_projectSystemCache.TryGetProjectRestoreInfo(ProjectFullPath, out var projectRestoreInfo, out _)) { return projectRestoreInfo.GetProjectSpec(ProjectFullPath); } @@ -129,9 +128,7 @@ protected override Task GetPackageSpecAsync(CancellationToken ct) { var projects = new List(); - DependencyGraphSpec projectRestoreInfo; - IReadOnlyList additionalMessages; - if (!_projectSystemCache.TryGetProjectRestoreInfo(ProjectFullPath, out projectRestoreInfo, out additionalMessages)) + if (!_projectSystemCache.TryGetProjectRestoreInfo(ProjectFullPath, out var projectRestoreInfo, out var additionalMessages)) { throw new ProjectNotNominatedException( string.Format(CultureInfo.CurrentCulture, Strings.ProjectNotLoaded_RestoreFailed, ProjectName)); @@ -282,8 +279,7 @@ public override async Task InstallPackageAsync( foreach (var framework in installationContext.SuccessfulFrameworks) { - string originalFramework; - if (!installationContext.OriginalFrameworks.TryGetValue(framework, out originalFramework)) + if (!installationContext.OriginalFrameworks.TryGetValue(framework, out var originalFramework)) { originalFramework = framework.GetShortFolderName(); } @@ -386,8 +382,7 @@ public override async Task UninstallPackageAsync(string packageId, BuildIn foreach (var framework in installationContext.SuccessfulFrameworks) { - string originalFramework; - if (!installationContext.OriginalFrameworks.TryGetValue(framework, out originalFramework)) + if (!installationContext.OriginalFrameworks.TryGetValue(framework, out var originalFramework)) { originalFramework = framework.GetShortFolderName(); } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/LegacyPackageReferenceProject.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/LegacyPackageReferenceProject.cs index f694e71a66a..a64d6740218 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/LegacyPackageReferenceProject.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/LegacyPackageReferenceProject.cs @@ -115,8 +115,7 @@ protected override async Task GetAssetsFilePathAsync(bool shouldThrow) public override async Task<(IReadOnlyList dgSpecs, IReadOnlyList additionalMessages)> GetPackageSpecsAndAdditionalMessagesAsync(DependencyGraphCacheContext context) { - PackageSpec packageSpec; - if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out packageSpec)) + if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out var packageSpec)) { packageSpec = await GetPackageSpecAsync(context.Settings); if (packageSpec == null) diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/PackageReferenceProject.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/PackageReferenceProject.cs index fce38b7f914..acc642bf0c5 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/PackageReferenceProject.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/PackageReferenceProject.cs @@ -484,8 +484,7 @@ private static void MarkTransitiveOrigin(Dictionary tra visited.Add(current.PackageIdentity); // visited // Lookup Transitive Origins Cache - TransitiveEntry cachedEntry; - if (!transitiveOriginsCache.TryGetValue(current.PackageIdentity.Id, out cachedEntry)) + if (!transitiveOriginsCache.TryGetValue(current.PackageIdentity.Id, out var cachedEntry)) { cachedEntry = new Dictionary> { diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectSystemCache.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectSystemCache.cs index 372492693e3..4d15b995537 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectSystemCache.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/ProjectSystemCache.cs @@ -54,8 +54,7 @@ public bool TryGetNuGetProject(string name, out NuGetProject project) project = null; - CacheEntry cacheEntry; - if (TryGetCacheEntry(name, out cacheEntry)) + if (TryGetCacheEntry(name, out var cacheEntry)) { project = cacheEntry.NuGetProject; } @@ -72,8 +71,7 @@ public bool TryGetVsProjectAdapter(string name, out IVsProjectAdapter project) project = null; - CacheEntry cacheEntry; - if (TryGetCacheEntry(name, out cacheEntry)) + if (TryGetCacheEntry(name, out var cacheEntry)) { project = cacheEntry.VsProjectAdapter; } @@ -91,8 +89,7 @@ public bool TryGetProjectRestoreInfo(string name, out DependencyGraphSpec projec projectRestoreInfo = null; additionalMessages = null; - CacheEntry cacheEntry; - if (TryGetCacheEntry(name, out cacheEntry)) + if (TryGetCacheEntry(name, out var cacheEntry)) { projectRestoreInfo = cacheEntry.ProjectRestoreInfo; additionalMessages = cacheEntry.AdditionalMessages; @@ -132,8 +129,7 @@ public void RemoveProject(string name) try { - ProjectNames projectNames; - if (_projectNamesCache.TryGetValue(name, out projectNames)) + if (_projectNamesCache.TryGetValue(name, out var projectNames)) { _readerWriterLock.EnterWriteLock(); @@ -217,8 +213,7 @@ public bool IsAmbiguous(string shortName) try { - HashSet values; - if (_shortNameCache.TryGetValue(shortName, out values)) + if (_shortNameCache.TryGetValue(shortName, out var values)) { return values.Count > 1; } @@ -329,8 +324,8 @@ private CacheEntry AddOrUpdateCacheEntry( { Debug.Assert(_readerWriterLock.IsWriteLockHeld); - CacheEntry newCacheEntry, oldCacheEntry; - if (_primaryCache.TryGetValue(primaryKey, out oldCacheEntry)) + CacheEntry newCacheEntry; + if (_primaryCache.TryGetValue(primaryKey, out var oldCacheEntry)) { newCacheEntry = updateEntryFactory(primaryKey, oldCacheEntry); _primaryCache[primaryKey] = newCacheEntry; @@ -381,8 +376,7 @@ private bool TryGetProjectNameByShortNameWithoutLock(string name, out ProjectNam projectNames = null; - HashSet values; - if (_shortNameCache.TryGetValue(name, out values)) + if (_shortNameCache.TryGetValue(name, out var values)) { // If there is only one project name instance, that means the short name is unambiguous, in which // case we can return that one project. @@ -401,8 +395,7 @@ private void AddShortName(ProjectNames projectNames) { Debug.Assert(_readerWriterLock.IsWriteLockHeld); - HashSet values; - if (!_shortNameCache.TryGetValue(projectNames.ShortName, out values)) + if (!_shortNameCache.TryGetValue(projectNames.ShortName, out var values)) { values = new HashSet(); _shortNameCache.Add(projectNames.ShortName, values); @@ -419,8 +412,7 @@ private void RemoveShortName(ProjectNames projectNames) { Debug.Assert(_readerWriterLock.IsWriteLockHeld); - HashSet values; - if (_shortNameCache.TryGetValue(projectNames.ShortName, out values)) + if (_shortNameCache.TryGetValue(projectNames.ShortName, out var values)) { values.Remove(projectNames); @@ -470,8 +462,7 @@ private bool TryGetCacheEntry(string secondaryKey, out CacheEntry cacheEntry) try { - ProjectNames primaryKey; - if (_projectNamesCache.TryGetValue(secondaryKey, out primaryKey) || + if (_projectNamesCache.TryGetValue(secondaryKey, out var primaryKey) || TryGetProjectNameByShortNameWithoutLock(secondaryKey, out primaryKey)) { return _primaryCache.TryGetValue(primaryKey.FullName, out cacheEntry); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/VsProjectAdapter.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/VsProjectAdapter.cs index c207b5a105c..3279974e21b 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/VsProjectAdapter.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Projects/VsProjectAdapter.cs @@ -69,8 +69,7 @@ public string ProjectId { get { - Guid id; - if (!_vsHierarchyItem.TryGetProjectId(out id)) + if (!_vsHierarchyItem.TryGetProjectId(out var id)) { id = Guid.Empty; } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/BindingRedirectResolver.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/BindingRedirectResolver.cs index 994eed6a33c..256b983502e 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/BindingRedirectResolver.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/BindingRedirectResolver.cs @@ -80,10 +80,9 @@ public static IEnumerable GetBindingRedirects(IEnumerable key = GetUniqueKey(referenceAssembly); - IAssembly targetAssembly; // If we have an assembly with the same unique key in our list of a different version then we want to use that version // then we want to add a redirect for that assembly - if (assemblyNameLookup.TryGetValue(key, out targetAssembly) + if (assemblyNameLookup.TryGetValue(key, out var targetAssembly) && targetAssembly.Version != referenceAssembly.Version) { // BUG #1158: Don't add binding redirects for assemblies without a strong name diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/RemoteAssembly.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/RemoteAssembly.cs index a1dbd2f773a..8ea5c644743 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/RemoteAssembly.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Runtime/RemoteAssembly.cs @@ -39,8 +39,7 @@ public void Load(string path) string fileName = Path.GetFileName(path).ToUpperInvariant(); var cacheKey = Tuple.Create(fileName, AssemblyName.GetAssemblyName(path).FullName); - Assembly assembly; - if (!_assemblyCache.TryGetValue(cacheKey, out assembly)) + if (!_assemblyCache.TryGetValue(cacheKey, out var assembly)) { // Load the assembly in a reflection only context assembly = Assembly.ReflectionOnlyLoadFrom(path); diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Setting/SettingsManagerWrapper.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Setting/SettingsManagerWrapper.cs index 6cee1834460..08a30adce4b 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Setting/SettingsManagerWrapper.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Setting/SettingsManagerWrapper.cs @@ -36,8 +36,7 @@ public ISettingsStore GetReadOnlySettingsStore() var settingsManager = await _settingsManager.GetValueAsync(); - IVsSettingsStore settingsStore; - var hr = settingsManager.GetReadOnlySettingsStore((uint)__VsSettingsScope.SettingsScope_UserSettings, out settingsStore); + var hr = settingsManager.GetReadOnlySettingsStore((uint)__VsSettingsScope.SettingsScope_UserSettings, out var settingsStore); if (ErrorHandler.Succeeded(hr) && settingsStore != null) { @@ -56,8 +55,7 @@ public IWritableSettingsStore GetWritableSettingsStore() var settingsManager = await _settingsManager.GetValueAsync(); - IVsWritableSettingsStore settingsStore; - var hr = settingsManager.GetWritableSettingsStore((uint)__VsSettingsScope.SettingsScope_UserSettings, out settingsStore); + var hr = settingsManager.GetWritableSettingsStore((uint)__VsSettingsScope.SettingsScope_UserSettings, out var settingsStore); if (ErrorHandler.Succeeded(hr) && settingsStore != null) { diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/SourceControl/VsSourceControlTracker.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/SourceControl/VsSourceControlTracker.cs index 1921f013b9a..37bbff681dd 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/SourceControl/VsSourceControlTracker.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/SourceControl/VsSourceControlTracker.cs @@ -112,8 +112,7 @@ private void StartTracking() { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - uint cookie; - if (ProjectTracker.AdviseTrackProjectDocumentsEvents(_projectDocumentListener, out cookie) == VSConstants.S_OK) + if (ProjectTracker.AdviseTrackProjectDocumentsEvents(_projectDocumentListener, out var cookie) == VSConstants.S_OK) { _trackingCookie = cookie; } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/EnvDTEProjectUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/EnvDTEProjectUtility.cs index 606324d60ea..2b320fd2414 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/EnvDTEProjectUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/EnvDTEProjectUtility.cs @@ -149,10 +149,8 @@ public static async Task ContainsFileAsync(EnvDTE.Project envDTEProject, s await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - EnvDTE.ProjectItem subFolder; - var envDTEProjectItems = GetProjectItems(parentItem); - if (TryGetFolder(envDTEProjectItems, folderName, out subFolder)) + if (TryGetFolder(envDTEProjectItems, folderName, out var subFolder)) { // Get the sub folder return subFolder; @@ -212,8 +210,7 @@ private static async Task IncludeExistingFolderToProjectAsync(EnvDTE.Proje var projectHierarchy = (IVsUIHierarchy)(await envDTEProject.ToVsHierarchyAsync()); - uint itemId; - var hr = projectHierarchy.ParseCanonicalName(folderRelativePath, out itemId); + var hr = projectHierarchy.ParseCanonicalName(folderRelativePath, out var itemId); if (!ErrorHandler.Succeeded(hr)) { return false; @@ -254,8 +251,7 @@ private static bool TryGetNestedFile(EnvDTE.ProjectItems envDTEProjectItems, str { ThreadHelper.ThrowIfNotOnUIThread(); - string parentFileName; - if (!KnownNestedFiles.TryGetValue(name, out parentFileName)) + if (!KnownNestedFiles.TryGetValue(name, out var parentFileName)) { parentFileName = Path.GetFileNameWithoutExtension(name); } @@ -326,11 +322,10 @@ private static EnvDTE.ProjectItems GetProjectItems(object parent) var container = await GetProjectItemsAsync(envDTEProject, folderPath, createIfNotExists: false); - EnvDTE.ProjectItem projectItem; // If we couldn't get the folder, or the child item doesn't exist, return null if (container == null || - (!TryGetFile(container, itemName, out projectItem) && + (!TryGetFile(container, itemName, out var projectItem) && !TryGetFolder(container, itemName, out projectItem))) { return null; @@ -470,8 +465,7 @@ internal static async Task> GetAssemblyClosureAsync(EnvDTE.Proje { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - HashSet assemblies; - if (visitedProjects.TryGetValue(envDTEProject.UniqueName, out assemblies)) + if (visitedProjects.TryGetValue(envDTEProject.UniqueName, out var assemblies)) { return assemblies; } diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs index 38b1a90e30e..b27ad8fb9a2 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/NuGetProjectUpgradeUtility.cs @@ -128,8 +128,7 @@ public static string GetSelectedFileName(IVsMonitorSelection vsMonitorSelection) try { IVsMultiItemSelect multiItemSelect; - uint itemId; - if (vsMonitorSelection.GetCurrentSelection(out hHierarchy, out itemId, out multiItemSelect, out hContainer) != 0) + if (vsMonitorSelection.GetCurrentSelection(out hHierarchy, out var itemId, out multiItemSelect, out hContainer) != 0) { return string.Empty; } @@ -142,8 +141,8 @@ public static string GetSelectedFileName(IVsMonitorSelection vsMonitorSelection) { return string.Empty; } - string fileName; - hierarchy.GetCanonicalName(itemId, out fileName); + + hierarchy.GetCanonicalName(itemId, out var fileName); return fileName; } finally diff --git a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/TaskCombinators.cs b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/TaskCombinators.cs index fb14d7e79c3..4f8c4ef3d3d 100644 --- a/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/TaskCombinators.cs +++ b/src/NuGet.Clients/NuGet.PackageManagement.VisualStudio/Utility/TaskCombinators.cs @@ -27,8 +27,7 @@ public static async Task> ThrottledAsync( Func taskBody = async () => { - TSource source; - while (bag.TryTake(out source)) + while (bag.TryTake(out var source)) { var value = await valueSelector(source, cancellationToken); values.Enqueue(value); diff --git a/src/NuGet.Clients/NuGet.SolutionRestoreManager/RestoreOperationLogger.cs b/src/NuGet.Clients/NuGet.SolutionRestoreManager/RestoreOperationLogger.cs index a2616665e0e..cfda1a7f2fa 100644 --- a/src/NuGet.Clients/NuGet.SolutionRestoreManager/RestoreOperationLogger.cs +++ b/src/NuGet.Clients/NuGet.SolutionRestoreManager/RestoreOperationLogger.cs @@ -534,8 +534,7 @@ public static async Task StartAsync( var statusBar = await asyncServiceProvider.GetServiceAsync(); // Make sure the status bar is not frozen - int frozen; - statusBar.IsFrozen(out frozen); + statusBar.IsFrozen(out var frozen); if (frozen != 0) { @@ -568,8 +567,7 @@ public override async Task ReportProgressAsync( await _taskFactory.SwitchToMainThreadAsync(); // Make sure the status bar is not frozen - int frozen; - _statusBar.IsFrozen(out frozen); + _statusBar.IsFrozen(out var frozen); if (frozen != 0) { diff --git a/src/NuGet.Clients/NuGet.SolutionRestoreManager/SolutionRestoreWorker.cs b/src/NuGet.Clients/NuGet.SolutionRestoreManager/SolutionRestoreWorker.cs index 7d106a4acdb..9ea4a599ce4 100644 --- a/src/NuGet.Clients/NuGet.SolutionRestoreManager/SolutionRestoreWorker.cs +++ b/src/NuGet.Clients/NuGet.SolutionRestoreManager/SolutionRestoreWorker.cs @@ -224,8 +224,7 @@ private async Task IsSolutionFullyLoadedAsync() return false; } - object value; - var hr = vsSolution.GetProperty((int)(__VSPROPID4.VSPROPID_IsSolutionFullyLoaded), out value); + var hr = vsSolution.GetProperty((int)(__VSPROPID4.VSPROPID_IsSolutionFullyLoaded), out var value); ErrorHandler.ThrowOnFailure(hr); return (bool)value; @@ -526,13 +525,11 @@ await _solutionLoadedEvent.WaitAsync() while (!_pendingRequests.Value.IsCompleted && !token.IsCancellationRequested) { - SolutionRestoreRequest next; - // check if there are pending nominations var isAllProjectsNominated = await _solutionManager.Value.IsAllProjectsNominatedAsync(); // Try to get a request without a timeout. We don't want to *block* the threadpool thread. - if (!_pendingRequests.Value.TryTake(out next, millisecondsTimeout: 0, token)) + if (!_pendingRequests.Value.TryTake(out var next, millisecondsTimeout: 0, token)) { if (isAllProjectsNominated) { diff --git a/src/NuGet.Clients/NuGet.SolutionRestoreManager/VsSolutionRestoreService.cs b/src/NuGet.Clients/NuGet.SolutionRestoreManager/VsSolutionRestoreService.cs index 217fd407e4f..d7a55b5cfcd 100644 --- a/src/NuGet.Clients/NuGet.SolutionRestoreManager/VsSolutionRestoreService.cs +++ b/src/NuGet.Clients/NuGet.SolutionRestoreManager/VsSolutionRestoreService.cs @@ -553,8 +553,7 @@ async Task IsSolutionFullyLoadedAsync(IVsSolution2 vsSolution) return false; } - object value; - var hr = vsSolution.GetProperty((int)(__VSPROPID4.VSPROPID_IsSolutionFullyLoaded), out value); + var hr = vsSolution.GetProperty((int)(__VSPROPID4.VSPROPID_IsSolutionFullyLoaded), out var value); ErrorHandler.ThrowOnFailure(hr); return (bool)value; diff --git a/src/NuGet.Clients/NuGet.SolutionRestoreManager/VulnerablePackagesInfoBar.cs b/src/NuGet.Clients/NuGet.SolutionRestoreManager/VulnerablePackagesInfoBar.cs index e7155dd21c3..6aa35281132 100644 --- a/src/NuGet.Clients/NuGet.SolutionRestoreManager/VulnerablePackagesInfoBar.cs +++ b/src/NuGet.Clients/NuGet.SolutionRestoreManager/VulnerablePackagesInfoBar.cs @@ -106,8 +106,7 @@ private async Task CreateInfoBar() return; } - object tempObject; - int hostBarCode = windowFrame.GetProperty((int)__VSFPROPID7.VSFPROPID_InfoBarHost, out tempObject); + int hostBarCode = windowFrame.GetProperty((int)__VSFPROPID7.VSFPROPID_InfoBarHost, out var tempObject); if (ErrorHandler.Failed(hostBarCode)) { Exception exception = new Exception(string.Format(CultureInfo.CurrentCulture, "Unable to find InfoBarHost. HRRESULT {0}", hostBarCode)); diff --git a/src/NuGet.Clients/NuGet.Tools/Commands/ShowErrorsCommand.cs b/src/NuGet.Clients/NuGet.Tools/Commands/ShowErrorsCommand.cs index 204fe23edcc..0fd37c7a375 100644 --- a/src/NuGet.Clients/NuGet.Tools/Commands/ShowErrorsCommand.cs +++ b/src/NuGet.Clients/NuGet.Tools/Commands/ShowErrorsCommand.cs @@ -64,13 +64,11 @@ public void Execute(object parameter) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - IVsWindowFrame toolWindow = null; - _vsUiShell.Value.FindToolWindow(0, ref GuidList.guidVsWindowKindOutput, out toolWindow); + _vsUiShell.Value.FindToolWindow(0, ref GuidList.guidVsWindowKindOutput, out var toolWindow); toolWindow?.Show(); - IVsOutputWindowPane pane; Guid outputWindowPaneId = NuGetConsole.GuidList.NuGetOutputWindowPaneGuid; - if (_vsOutputWindow.Value.GetPane(ref outputWindowPaneId, out pane) == VSConstants.S_OK) + if (_vsOutputWindow.Value.GetPane(ref outputWindowPaneId, out var pane) == VSConstants.S_OK) { NuGetConsole.GuidList.NuGetOutputWindowPaneGuid = outputWindowPaneId; pane.Activate(); diff --git a/src/NuGet.Clients/NuGet.Tools/NuGetPackage.cs b/src/NuGet.Clients/NuGet.Tools/NuGetPackage.cs index 8ec4a70e31d..65fd65d1a14 100644 --- a/src/NuGet.Clients/NuGet.Tools/NuGetPackage.cs +++ b/src/NuGet.Clients/NuGet.Tools/NuGetPackage.cs @@ -408,10 +408,9 @@ private async Task FindExistingWindowFrameAsync(Project project) var uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); foreach (var windowFrame in VsUtility.GetDocumentWindows(uiShell)) { - object docView; var hr = windowFrame.GetProperty( (int)__VSFPROPID.VSFPROPID_DocView, - out docView); + out var docView); if (hr == VSConstants.S_OK && docView is PackageManagerWindowPane) { @@ -716,10 +715,9 @@ private async Task FindExistingSolutionWindowFrameAsync() var uiShell = await this.GetServiceAsync(); foreach (var windowFrame in VsUtility.GetDocumentWindows(uiShell)) { - object property; var hr = windowFrame.GetProperty( (int)__VSFPROPID.VSFPROPID_DocData, - out property); + out var property); var packageManagerControl = VsUtility.GetPackageManagerControl(windowFrame); if (hr == VSConstants.S_OK && diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/BindingRedirectBehavior.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/BindingRedirectBehavior.cs index f0d1d61a5dc..19ddbb91e9c 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/BindingRedirectBehavior.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/BindingRedirectBehavior.cs @@ -74,11 +74,8 @@ private static bool IsSet(string value, bool defaultValue) value = value.Trim(); - bool boolResult; - int intResult; - - var result = ((bool.TryParse(value, out boolResult) && boolResult) || - (int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out intResult) && (intResult == 1))); + var result = ((bool.TryParse(value, out var boolResult) && boolResult) || + (int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var intResult) && (intResult == 1))); return result; } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/ErrorListTableDataSource.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/ErrorListTableDataSource.cs index d4fb3983d11..9d64552023a 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/ErrorListTableDataSource.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/ErrorListTableDataSource.cs @@ -235,10 +235,9 @@ public ErrorListTableEntry[] GetEntries() private static bool IsNuGetEntry(ITableEntryHandle entry) { - object sourceObj; return (entry != null - && entry.TryGetValue(StandardTableColumnDefinitions.ErrorSource, out sourceObj) - && StringComparer.Ordinal.Equals(ErrorListTableEntry.ErrorSouce, (sourceObj as string))); + && entry.TryGetValue(StandardTableColumnDefinitions.ErrorSource, out var sourceObj) + && StringComparer.Ordinal.Equals(ErrorListTableEntry.ErrorSouce, (sourceObj as string))); } public void Dispose() diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/EnvDteProjectExtensions.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/EnvDteProjectExtensions.cs index 46c8d5dec83..b1f40755e0a 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/EnvDteProjectExtensions.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/EnvDteProjectExtensions.cs @@ -28,11 +28,9 @@ public static async Task ToVsHierarchyAsync(this EnvDTE.Project pr { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - IVsHierarchy hierarchy; - // Get the vs solution var solution = await ServiceLocator.GetGlobalServiceAsync(); - int hr = solution.GetProjectOfUniqueName(project.GetUniqueName(), out hierarchy); + int hr = solution.GetProjectOfUniqueName(project.GetUniqueName(), out var hierarchy); if (hr != VSConstants.S_OK) { diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs index d92c7522978..9947cbb8b1a 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsHierarchyUtility.cs @@ -101,8 +101,7 @@ public static string[] GetProjectTypeGuidsFromHierarchy(IVsHierarchy hierarchy) var aggregatableProject = hierarchy as IVsAggregatableProject; if (aggregatableProject != null) { - string projectTypeGuids; - var hr = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids); + var hr = aggregatableProject.GetAggregateProjectTypeGuids(out var projectTypeGuids); ErrorHandler.ThrowOnFailure(hr); return projectTypeGuids.Split([';'], StringSplitOptions.RemoveEmptyEntries); @@ -136,9 +135,8 @@ public static EnvDTE.Project GetProjectFromHierarchy(IVsHierarchy pHierarchy) // Set it to null to avoid unassigned local variable warning EnvDTE.Project project = null; - object projectObject; - if (pHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out projectObject) >= 0) + if (pHierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out var projectObject) >= 0) { project = (EnvDTE.Project)projectObject; } @@ -177,8 +175,7 @@ public static async Task CollapseAllNodesAsync(IDictionary()) { - ISet expandedNodes; - if (ignoreNodes.TryGetValue(project.GetUniqueName(), out expandedNodes) + if (ignoreNodes.TryGetValue(project.GetUniqueName(), out var expandedNodes) && expandedNodes != null) { @@ -320,10 +317,9 @@ private static async Task IsVsHierarchyItemExpandedAsync(VsHierarchyItem h } const uint expandedStateMask = (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded; - uint itemState; await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - uiWindow.GetItemState(AsVsUIHierarchy(hierarchyItem), hierarchyItem.VsItemID, expandedStateMask, out itemState); + uiWindow.GetItemState(AsVsUIHierarchy(hierarchyItem), hierarchyItem.VsItemID, expandedStateMask, out var itemState); return ((__VSHIERARCHYITEMSTATE)itemState == __VSHIERARCHYITEMSTATE.HIS_Expanded); } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsMonitorSelectionExtensions.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsMonitorSelectionExtensions.cs index 4343e77d49e..c56306a8c13 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsMonitorSelectionExtensions.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/IDE/VsMonitorSelectionExtensions.cs @@ -18,15 +18,13 @@ public static EnvDTE.Project GetActiveProject(this IVsMonitorSelection vsMonitor ThreadHelper.ThrowIfNotOnUIThread(); IntPtr ppHier = IntPtr.Zero; - uint pitemid; - IVsMultiItemSelect ppMIS; IntPtr ppSC = IntPtr.Zero; try { IVsHierarchy hierarchy = null; - vsMonitorSelection.GetCurrentSelection(out ppHier, out pitemid, out ppMIS, out ppSC); + vsMonitorSelection.GetCurrentSelection(out ppHier, out var pitemid, out var ppMIS, out ppSC); if (ppHier == IntPtr.Zero) { return null; @@ -49,8 +47,7 @@ public static EnvDTE.Project GetActiveProject(this IVsMonitorSelection vsMonitor if (hierarchy != null) { - object project; - if (hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out project) >= 0) + if (hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out var project) >= 0) { return project as EnvDTE.Project; } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/PackageManagementFormat.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/PackageManagementFormat.cs index e3d92baa489..c3b47e67bec 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/PackageManagementFormat.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/PackageManagementFormat.cs @@ -125,11 +125,8 @@ private static bool ParseValue(string value, bool defaultValue) value = value.Trim(); - bool boolResult; - int intResult; - - var result = ((bool.TryParse(value, out boolResult) && boolResult) || - (int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out intResult) && (intResult == 1))); + var result = ((bool.TryParse(value, out var boolResult) && boolResult) || + (int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var intResult) && (intResult == 1))); return result; } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/ProjectHelper.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/ProjectHelper.cs index 0565257d93d..2d11ba8d387 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/ProjectHelper.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/ProjectHelper.cs @@ -57,8 +57,7 @@ private static UnconfiguredProject GetUnconfiguredProject(IVsProject project) IVsHierarchy hierarchy = project as IVsHierarchy; if (hierarchy != null) { - object extObject; - if (ErrorHandler.Succeeded(hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extObject))) + if (ErrorHandler.Succeeded(hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out var extObject))) { Project dteProject = extObject as Project; if (dteProject != null) diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Common/WindowFrameHelper.cs b/src/NuGet.Clients/NuGet.VisualStudio.Common/WindowFrameHelper.cs index 9faf8821d5f..bf9e8221557 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Common/WindowFrameHelper.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Common/WindowFrameHelper.cs @@ -13,8 +13,7 @@ public static void AddF1HelpKeyword(IVsWindowFrame windowFrame, string keywordVa { ThreadHelper.ThrowIfNotOnUIThread(); // Set F1 help keyword - object varUserContext = null; - if (ErrorHandler.Succeeded(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_UserContext, out varUserContext))) + if (ErrorHandler.Succeeded(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_UserContext, out var varUserContext))) { var userContext = varUserContext as IVsUserContext; if (userContext != null) diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/Extensibility/VsPackageInstallerServices.cs b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/Extensibility/VsPackageInstallerServices.cs index 92bae8ee10c..ad79e8650f4 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/Extensibility/VsPackageInstallerServices.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/Extensibility/VsPackageInstallerServices.cs @@ -324,8 +324,7 @@ public bool IsPackageInstalled(Project project, string packageId, SemanticVersio const string eventName = nameof(IVsPackageInstallerServices) + "." + nameof(IsPackageInstalled) + ".3"; using var _ = NuGetETW.ExtensibilityEventSource.StartStopEvent(eventName); - NuGetVersion nugetVersion; - if (NuGetVersion.TryParse(version.ToString(), out nugetVersion)) + if (NuGetVersion.TryParse(version.ToString(), out var nugetVersion)) { return IsPackageInstalled(project, packageId, nugetVersion); } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledPackageInstaller.cs b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledPackageInstaller.cs index cc05000f96d..5a2c009b51c 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledPackageInstaller.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledPackageInstaller.cs @@ -77,9 +77,8 @@ public PreinstalledPackageInstaller( internal string GetExtensionRepositoryPath(string extensionId, object vsExtensionManager, Action throwingErrorHandler) { var extensionManagerShim = new ExtensionManagerShim(vsExtensionManager, throwingErrorHandler); - string installPath; - if (!extensionManagerShim.TryGetExtensionInstallPath(extensionId, out installPath)) + if (!extensionManagerShim.TryGetExtensionInstallPath(extensionId, out var installPath)) { throwingErrorHandler(string.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_InvalidExtensionId, extensionId)); diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledRepositoryProvider.cs b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledRepositoryProvider.cs index ac939587d30..f4103bc0e71 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledRepositoryProvider.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/PreinstalledRepositoryProvider.cs @@ -118,9 +118,8 @@ public Configuration.IPackageSourceProvider PackageSourceProvider private string GetExtensionRepositoryPath(string extensionId) { var extensionManagerShim = new ExtensionManagerShim(extensionManager: null, errorHandler: _errorHandler); - string installPath; - if (!extensionManagerShim.TryGetExtensionInstallPath(extensionId, out installPath)) + if (!extensionManagerShim.TryGetExtensionInstallPath(extensionId, out var installPath)) { var errorMessage = string.Format(CultureInfo.CurrentCulture, VsResources.PreinstalledPackages_InvalidExtensionId, extensionId); _errorHandler(errorMessage); diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/VsTemplateWizard.cs b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/VsTemplateWizard.cs index 674a8df85fc..7386c4c15d2 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Implementation/VsTemplateWizard.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Implementation/VsTemplateWizard.cs @@ -313,8 +313,7 @@ private async Task RunDesignTimeBuildAsync(Project project) if (solution != null) { - IVsHierarchy hierarchy; - if (ErrorHandler.Succeeded(solution.GetProjectOfUniqueName(project.UniqueName, out hierarchy)) + if (ErrorHandler.Succeeded(solution.GetProjectOfUniqueName(project.UniqueName, out var hierarchy)) && hierarchy != null) { var solutionBuild = hierarchy as IVsProjectBuildSystem; @@ -394,8 +393,7 @@ private void AddTemplateParameters(Dictionary replacementsDictio // add the $nugetpackagesfolder$ parameter which returns relative path to the solution's packages folder. // this is used by project templates to include assembly references directly inside the template project file // without relying on nuget to install the actual packages. - string targetInstallDir; - if (replacementsDictionary.TryGetValue("$destinationdirectory$", out targetInstallDir)) + if (replacementsDictionary.TryGetValue("$destinationdirectory$", out var targetInstallDir)) { string solutionRepositoryPath = null; if (_dte.Solution != null @@ -526,15 +524,13 @@ internal static string DetermineSolutionDirectory(Dictionary rep // Is $specifiedsolutionname$ null or empty? We're definitely in the solution // in same directory as project case. - string solutionName; - string solutionDir; - bool ignoreSolutionDir = (replacementsDictionary.TryGetValue("$specifiedsolutionname$", out solutionName) && String.IsNullOrEmpty(solutionName)); + bool ignoreSolutionDir = (replacementsDictionary.TryGetValue("$specifiedsolutionname$", out var solutionName) && String.IsNullOrEmpty(solutionName)); // We check $destinationdirectory$ twice because we want the following precedence: // 1. If $specifiedsolutionname$ == null, ALWAYS use $destinationdirectory$ // 2. Otherwise, use $solutiondirectory$ if available // 3. If $solutiondirectory$ is not available, use $destinationdirectory$. - if ((ignoreSolutionDir && replacementsDictionary.TryGetValue("$destinationdirectory$", out solutionDir)) + if ((ignoreSolutionDir && replacementsDictionary.TryGetValue("$destinationdirectory$", out var solutionDir)) || replacementsDictionary.TryGetValue("$solutiondirectory$", out solutionDir) || replacementsDictionary.TryGetValue("$destinationdirectory$", out solutionDir)) { diff --git a/src/NuGet.Clients/NuGet.VisualStudio.Internal.Contracts/ProjectMetadataContextInfo.cs b/src/NuGet.Clients/NuGet.VisualStudio.Internal.Contracts/ProjectMetadataContextInfo.cs index 24503b7c4e1..0227b44a9d0 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.Internal.Contracts/ProjectMetadataContextInfo.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.Internal.Contracts/ProjectMetadataContextInfo.cs @@ -47,9 +47,8 @@ public static ProjectMetadataContextInfo Create(IReadOnlyDictionary? supportedFrameworks = null; NuGetFramework? targetFramework = null; string? uniqueName = null; - object? value; - if (projectMetadata.TryGetValue(NuGetProjectMetadataKeys.FullPath, out value)) + if (projectMetadata.TryGetValue(NuGetProjectMetadataKeys.FullPath, out var value)) { fullPath = value as string; } diff --git a/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/PackageManagerUICommandHandler.cs b/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/PackageManagerUICommandHandler.cs index d6e81c6be84..fbc99b0ae8a 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/PackageManagerUICommandHandler.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/PackageManagerUICommandHandler.cs @@ -262,8 +262,7 @@ private async ValueTask CreateToolWindowAsync(WorkspaceVisualNod var uiShell = await _asyncServiceProvider.GetServiceAsync(); Assumes.Present(uiShell); - uint toolWindowId; - bool foundToolWindowId = _projectGuidToToolWindowId.TryGetValue(projectGuid.ToString(), out toolWindowId); + bool foundToolWindowId = _projectGuidToToolWindowId.TryGetValue(projectGuid.ToString(), out var toolWindowId); const uint FTW_none = 0; if (foundToolWindowId) @@ -338,8 +337,7 @@ private async Task FindExistingSolutionWindowFrameAsync() var uiShell = await _asyncServiceProvider.GetServiceAsync(); foreach (var windowFrame in VsUtility.GetDocumentWindows(uiShell)) { - object property; - var hr = windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out property); + var hr = windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var property); var packageManagerControl = VsUtility.GetPackageManagerControl(windowFrame); if (hr == VSConstants.S_OK && property is IVsSolution diff --git a/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/RestoreCommandHandler.cs b/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/RestoreCommandHandler.cs index ae4e2e0094a..6b54ee52d16 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/RestoreCommandHandler.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio.OnlineEnvironment.Client/SolutionExplorer/RestoreCommandHandler.cs @@ -91,10 +91,9 @@ private async Task GetAndActivatePackageManagerOutputWindowAsync() fClearWithSolution: 0); ErrorHandler.ThrowOnFailure(hr); - IVsOutputWindowPane pane; hr = outputWindow.GetPane( ref GuidList.GuidNuGetOutputWindowPaneGuid, - out pane); + out var pane); ErrorHandler.ThrowOnFailure(hr); Guid outputToolWindow = VSConstants.StandardToolWindows.Output; diff --git a/src/NuGet.Clients/NuGet.VisualStudio/LegacyTypes/SemanticVersion.cs b/src/NuGet.Clients/NuGet.VisualStudio/LegacyTypes/SemanticVersion.cs index 586ab136316..699f884acde 100644 --- a/src/NuGet.Clients/NuGet.VisualStudio/LegacyTypes/SemanticVersion.cs +++ b/src/NuGet.Clients/NuGet.VisualStudio/LegacyTypes/SemanticVersion.cs @@ -140,8 +140,7 @@ public static SemanticVersion Parse(string version) throw new ArgumentException(Strings.Argument_Cannot_Be_Null_Or_Empty, nameof(version)); } - SemanticVersion semVer; - if (!TryParse(version, out semVer)) + if (!TryParse(version, out var semVer)) { throw new ArgumentException( message: string.Format(CultureInfo.CurrentCulture, Strings.SemanticVersionStringInvalid, version), @@ -175,8 +174,7 @@ private static bool TryParseInternal(string version, Regex regex, out SemanticVe } var match = regex.Match(version.Trim()); - Version versionValue; - if (!match.Success || !Version.TryParse(match.Groups["Version"].Value, out versionValue)) + if (!match.Success || !Version.TryParse(match.Groups["Version"].Value, out var versionValue)) { return false; } @@ -191,8 +189,7 @@ private static bool TryParseInternal(string version, Regex regex, out SemanticVe /// An instance of SemanticVersion if it parses correctly, null otherwise. public static SemanticVersion ParseOptionalVersion(string version) { - SemanticVersion semVer; - _ = TryParse(version, out semVer); + _ = TryParse(version, out var semVer); return semVer; } diff --git a/src/NuGet.Core/NuGet.Build.Tasks.Pack/GetPackOutputItemsTask.cs b/src/NuGet.Core/NuGet.Build.Tasks.Pack/GetPackOutputItemsTask.cs index 2e41c94313c..248cbc8e2e7 100644 --- a/src/NuGet.Core/NuGet.Build.Tasks.Pack/GetPackOutputItemsTask.cs +++ b/src/NuGet.Core/NuGet.Build.Tasks.Pack/GetPackOutputItemsTask.cs @@ -41,8 +41,7 @@ public class GetPackOutputItemsTask : Microsoft.Build.Utilities.Task public override bool Execute() { - NuGetVersion version; - if (!NuGetVersion.TryParse(PackageVersion, out version)) + if (!NuGetVersion.TryParse(PackageVersion, out var version)) { throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, diff --git a/src/NuGet.Core/NuGet.Build.Tasks.Pack/PackTaskLogic.cs b/src/NuGet.Core/NuGet.Build.Tasks.Pack/PackTaskLogic.cs index eaf370bf538..f84dd8c286e 100644 --- a/src/NuGet.Core/NuGet.Build.Tasks.Pack/PackTaskLogic.cs +++ b/src/NuGet.Core/NuGet.Build.Tasks.Pack/PackTaskLogic.cs @@ -48,8 +48,7 @@ public PackArgs GetPackArgs(IPackTaskRequest request) if (request.MinClientVersion != null) { - Version version; - if (!Version.TryParse(request.MinClientVersion, out version)) + if (!Version.TryParse(request.MinClientVersion, out var version)) { throw new PackagingException(NuGetLogCode.NU5022, string.Format( CultureInfo.CurrentCulture, @@ -138,8 +137,7 @@ public PackageBuilder GetPackageBuilder(IPackTaskRequest request) if (request.PackageVersion != null) { - NuGetVersion version; - if (!NuGetVersion.TryParse(request.PackageVersion, out version)) + if (!NuGetVersion.TryParse(request.PackageVersion, out var version)) { throw new PackagingException(NuGetLogCode.NU5024, string.Format( CultureInfo.CurrentCulture, @@ -163,8 +161,7 @@ public PackageBuilder GetPackageBuilder(IPackTaskRequest request) builder.Tags.AddRange(request.Tags); } - Uri tempUri; - if (Uri.TryCreate(request.LicenseUrl, UriKind.Absolute, out tempUri)) + if (Uri.TryCreate(request.LicenseUrl, UriKind.Absolute, out var tempUri)) { builder.LicenseUrl = tempUri; } @@ -193,8 +190,7 @@ public PackageBuilder GetPackageBuilder(IPackTaskRequest request) if (request.MinClientVersion != null) { - Version version; - if (!Version.TryParse(request.MinClientVersion, out version)) + if (!Version.TryParse(request.MinClientVersion, out var version)) { throw new PackagingException(NuGetLogCode.NU5022, string.Format( CultureInfo.CurrentCulture, @@ -477,8 +473,7 @@ private IEnumerable InitLibFiles(IMSBuildItem[] libFiles, IDictio throw new PackagingException(NuGetLogCode.NU5026, string.Format(CultureInfo.CurrentCulture, Strings.Error_FileNotFound, finalOutputPath)); } - string translated = null; - var succeeded = aliases.TryGetValue(targetFramework, out translated); + var succeeded = aliases.TryGetValue(targetFramework, out var translated); if (succeeded) { targetFramework = translated; @@ -515,8 +510,7 @@ private ISet ParseFrameworks(IPackTaskRequest requ { nugetFrameworks = new HashSet(request.TargetFrameworks.Select(targetFramework => { - string translated = null; - var succeeded = aliases.TryGetValue(targetFramework, out translated); + var succeeded = aliases.TryGetValue(targetFramework, out var translated); if (succeeded) { targetFramework = translated; @@ -854,8 +848,7 @@ private static void InitializeProjectDependencies( continue; } - HashSet dependencies; - if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies)) + if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out var dependencies)) { dependencies = new HashSet(); dependenciesByFramework[framework.FrameworkName] = dependencies; @@ -956,8 +949,7 @@ private static void AddDependencies( LockFile assetsFile, Dictionary> packageSpecificNoWarnProperties) { - HashSet dependencies; - if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies)) + if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out var dependencies)) { dependencies = new HashSet(); dependenciesByFramework[framework.FrameworkName] = dependencies; @@ -978,8 +970,7 @@ private static ImmutableArray AddDependencies( LockFile assetsFile, Dictionary> packageSpecificNoWarnProperties) { - HashSet dependencies; - if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies)) + if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out var dependencies)) { dependencies = new HashSet(); dependenciesByFramework[framework.FrameworkName] = dependencies; @@ -1035,9 +1026,7 @@ private static LibraryDependency GetUpdatedPackageDependency( if (packageDependency.NoWarn.Length > 0) { - HashSet<(NuGetLogCode, NuGetFramework)> nowarnProperties = null; - - if (!packageSpecificNoWarnProperties.TryGetValue(packageDependency.Name, out nowarnProperties)) + if (!packageSpecificNoWarnProperties.TryGetValue(packageDependency.Name, out var nowarnProperties)) { nowarnProperties = new HashSet<(NuGetLogCode, NuGetFramework)>(); } diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchArgs.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchArgs.cs index cb8399d843c..0f28d9ea4c3 100644 --- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchArgs.cs +++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchArgs.cs @@ -49,9 +49,7 @@ private int VerifyInt(string number, int defaultValue, string option) private PackageSearchFormat GetFormatFromOption(string format) { - PackageSearchFormat packageSearchFormat; - - if (!Enum.TryParse(format, ignoreCase: true, out packageSearchFormat)) + if (!Enum.TryParse(format, ignoreCase: true, out PackageSearchFormat packageSearchFormat)) { packageSearchFormat = PackageSearchFormat.Table; } @@ -61,9 +59,7 @@ private PackageSearchFormat GetFormatFromOption(string format) private PackageSearchVerbosity GetVerbosityFromOption(string verbosity) { - PackageSearchVerbosity packageSearchVerbosity; - - if (!Enum.TryParse(verbosity, ignoreCase: true, out packageSearchVerbosity)) + if (!Enum.TryParse(verbosity, ignoreCase: true, out PackageSearchVerbosity packageSearchVerbosity)) { packageSearchVerbosity = PackageSearchVerbosity.Normal; } diff --git a/src/NuGet.Core/NuGet.Commands/CommandArgs/PackArgs.cs b/src/NuGet.Core/NuGet.Commands/CommandArgs/PackArgs.cs index fa279684bbc..0b6fcba8cb1 100644 --- a/src/NuGet.Core/NuGet.Commands/CommandArgs/PackArgs.cs +++ b/src/NuGet.Core/NuGet.Commands/CommandArgs/PackArgs.cs @@ -67,8 +67,7 @@ public string CurrentDirectory public string GetPropertyValue(string propertyName) { - string value; - if (Properties.TryGetValue(propertyName, out value)) + if (Properties.TryGetValue(propertyName, out var value)) { return value; } diff --git a/src/NuGet.Core/NuGet.Commands/CommandRunners/PackCommandRunner.cs b/src/NuGet.Core/NuGet.Commands/CommandRunners/PackCommandRunner.cs index 9cdb2be425f..13030650124 100644 --- a/src/NuGet.Core/NuGet.Commands/CommandRunners/PackCommandRunner.cs +++ b/src/NuGet.Core/NuGet.Commands/CommandRunners/PackCommandRunner.cs @@ -410,8 +410,8 @@ private static void LoadProjectJsonFile( { builder.Owners.AddRange(spec.Owners); } - Uri tempUri; - if (Uri.TryCreate(spec.LicenseUrl, UriKind.Absolute, out tempUri)) + + if (Uri.TryCreate(spec.LicenseUrl, UriKind.Absolute, out var tempUri)) { builder.LicenseUrl = tempUri; } @@ -450,9 +450,7 @@ private static void LoadProjectJsonFile( { if (spec.PackOptions.IncludeExcludeFiles != null) { - string fullExclude; - string filesExclude; - CalculateExcludes(spec.PackOptions.IncludeExcludeFiles, out fullExclude, out filesExclude); + CalculateExcludes(spec.PackOptions.IncludeExcludeFiles, out var fullExclude, out var filesExclude); if (spec.PackOptions.IncludeExcludeFiles.Include != null) { @@ -477,9 +475,7 @@ private static void LoadProjectJsonFile( { foreach (KeyValuePair map in spec.PackOptions.Mappings) { - string fullExclude; - string filesExclude; - CalculateExcludes(map.Value, out fullExclude, out filesExclude); + CalculateExcludes(map.Value, out var fullExclude, out var filesExclude); if (map.Value.Include != null) { diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/CompatibilityChecker.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/CompatibilityChecker.cs index 9f3d861148f..ef8586cd6a8 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/CompatibilityChecker.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/CompatibilityChecker.cs @@ -111,8 +111,7 @@ internal async Task CheckAsync( } // Find the include/exclude flags for this package - LibraryIncludeFlags packageIncludeFlags; - if (!includeFlags.TryGetValue(node.Key.Name, out packageIncludeFlags)) + if (!includeFlags.TryGetValue(node.Key.Name, out var packageIncludeFlags)) { packageIncludeFlags = LibraryIncludeFlags.All; } @@ -297,10 +296,9 @@ private static List GetProjectFrameworks(Library localLibrary) { var available = new List(); - object frameworksObject; if (localLibrary.Items.TryGetValue( - KnownLibraryProperties.ProjectFrameworks, - out frameworksObject)) + KnownLibraryProperties.ProjectFrameworks, + out var frameworksObject)) { available = (List)frameworksObject; } @@ -310,10 +308,9 @@ private static List GetProjectFrameworks(Library localLibrary) private static bool IsProjectFrameworkCompatible(Library library) { - object frameworkInfoObject; if (library.Items.TryGetValue( - KnownLibraryProperties.TargetFrameworkInformation, - out frameworkInfoObject)) + KnownLibraryProperties.TargetFrameworkInformation, + out var frameworkInfoObject)) { var targetFrameworkInformation = (TargetFrameworkInformation)frameworkInfoObject; diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/ContentFiles/ContentFileUtils.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/ContentFiles/ContentFileUtils.cs index ff9880bc291..78c630189ca 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/ContentFiles/ContentFileUtils.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/ContentFiles/ContentFileUtils.cs @@ -37,8 +37,7 @@ internal static List GetContentGroupsForFramework( { var codeLanguage = (string)group.Properties[ManagedCodeConventions.PropertyNames.CodeLanguage]; - List index; - if (!groupsByLanguage.TryGetValue(codeLanguage, out index)) + if (!groupsByLanguage.TryGetValue(codeLanguage, out var index)) { index = new List(1); groupsByLanguage.Add(codeLanguage, index); diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/LockFileBuilder.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/LockFileBuilder.cs index bbe9dfcd8fc..d45edfaf891 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/LockFileBuilder.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/LockFileBuilder.cs @@ -110,8 +110,7 @@ public LockFile CreateLockFile(LockFile previousLockFile, } // The msbuild project path if it exists - object msbuildPath; - if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out msbuildPath)) + if (localMatch.LocalLibrary.Items.TryGetValue(KnownLibraryProperties.MSBuildProjectPath, out var msbuildPath)) { var msbuildRelativePath = PathUtility.GetRelativePath( project.FilePath, @@ -196,8 +195,7 @@ public LockFile CreateLockFile(LockFile previousLockFile, var library = graphItem.Key; // include flags - LibraryIncludeFlags includeFlags; - if (!flattenedFlags.TryGetValue(library.Name, out includeFlags)) + if (!flattenedFlags.TryGetValue(library.Name, out var includeFlags)) { includeFlags = ~LibraryIncludeFlags.ContentFiles; } diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs index a046fd1a0bd..53513ee8aa7 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreCommand.cs @@ -368,9 +368,8 @@ public async Task InstallPackagesAsync( var tasks = Enumerable.Range(0, threadCount) .Select(async _ => { - RemoteMatch match; var result = true; - while (bag.TryTake(out match)) + while (bag.TryTake(out var match)) { result &= await InstallPackageAsync(match, userPackageFolder, _request.PackageExtractionContext, token); } diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/DependencyGraphSpecRequestProvider.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/DependencyGraphSpecRequestProvider.cs index 0f9dc537e73..0f8df629552 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/DependencyGraphSpecRequestProvider.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/DependencyGraphSpecRequestProvider.cs @@ -273,8 +273,7 @@ private static void CollectReferences( { foreach (var child in root.ExternalProjectReferences) { - ExternalProjectReference childProject; - if (!allProjects.TryGetValue(child, out childProject)) + if (!allProjects.TryGetValue(child, out var childProject)) { // Let the resolver handle this later Debug.Fail($"Missing project {childProject}"); diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/MSBuildItem.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/MSBuildItem.cs index 5b05e5693d2..e02f7082c4e 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/MSBuildItem.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RequestFactory/MSBuildItem.cs @@ -53,8 +53,7 @@ public string GetProperty(string property) /// public string GetProperty(string property, bool trim) { - string val; - if (_metadata.TryGetValue(property, out val) && val != null) + if (_metadata.TryGetValue(property, out var val) && val != null) { if (trim) { diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreTargetGraph.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreTargetGraph.cs index 20ee41d7699..028c2957c35 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreTargetGraph.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/RestoreTargetGraph.cs @@ -127,8 +127,7 @@ public static RestoreTargetGraph Create( if (node.Disposition == Disposition.Acceptable) { // This wasn't resolved. It's a conflict. - HashSet ranges; - if (!conflicts.TryGetValue(node.Key.Name, out ranges)) + if (!conflicts.TryGetValue(node.Key.Name, out var ranges)) { ranges = new HashSet(); conflicts[node.Key.Name] = ranges; diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/IncludeFlagUtils.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/IncludeFlagUtils.cs index 055a462bd33..96ecc92fb6e 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/IncludeFlagUtils.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/IncludeFlagUtils.cs @@ -18,8 +18,7 @@ internal static Dictionary FlattenDependencyTypes( PackageSpec project, RestoreTargetGraph graph) { - Dictionary flattenedFlags; - if (!includeFlagGraphs.TryGetValue(graph, out flattenedFlags)) + if (!includeFlagGraphs.TryGetValue(graph, out var flattenedFlags)) { flattenedFlags = FlattenDependencyTypes(graph, project); includeFlagGraphs.Add(graph, flattenedFlags); @@ -121,8 +120,7 @@ private static void FlattenDependencyTypesUnified( var rootId = node.Item.Key.Name; // Combine results on the way up - LibraryIncludeFlags currentTypes; - if (result.TryGetValue(rootId, out currentTypes)) + if (result.TryGetValue(rootId, out var currentTypes)) { if ((node.DependencyType & currentTypes) == node.DependencyType) { @@ -150,8 +148,7 @@ private static void FlattenDependencyTypesUnified( // resolution phase. // Note that we cannot stop here if there are no flags since we still need to mark // the child nodes as having no flags. SuppressParent=all is a special case. - GraphItem child; - if (unifiedNodes.TryGetValue(dependency.Name, out child) + if (unifiedNodes.TryGetValue(dependency.Name, out var child) && dependency.SuppressParent != LibraryIncludeFlags.All) { // intersect the edges and remove any suppressParent flags diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/LockFileUtils.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/LockFileUtils.cs index a1ba4b8e609..9a568f6309c 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/LockFileUtils.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/LockFileUtils.cs @@ -524,10 +524,9 @@ public static LockFileTargetLibrary CreateLockFileTargetProject( // Target framework information is optional and may not exist for csproj projects // that do not have a project.json file. string projectFramework = null; - object frameworkInfoObject; if (localMatch.LocalLibrary.Items.TryGetValue( - KnownLibraryProperties.TargetFrameworkInformation, - out frameworkInfoObject)) + KnownLibraryProperties.TargetFrameworkInformation, + out var frameworkInfoObject)) { // Retrieve the resolved framework name, if this is null it means that the // project is incompatible. This is marked as Unsupported. @@ -642,19 +641,17 @@ public static LockFileTargetLibrary CreateLockFileTargetProject( } // Add frameworkAssemblies for projects - object frameworkAssembliesObject; if (localMatch.LocalLibrary.Items.TryGetValue( - KnownLibraryProperties.FrameworkAssemblies, - out frameworkAssembliesObject)) + KnownLibraryProperties.FrameworkAssemblies, + out var frameworkAssembliesObject)) { projectLib.FrameworkAssemblies.AddRange((List)frameworkAssembliesObject); } // Add frameworkReferences for projects - object frameworkReferencesObject; if (localMatch.LocalLibrary.Items.TryGetValue( - KnownLibraryProperties.FrameworkReferences, - out frameworkReferencesObject)) + KnownLibraryProperties.FrameworkReferences, + out var frameworkReferencesObject)) { projectLib.FrameworkReferences.AddRange( ((IReadOnlyCollection)frameworkReferencesObject) @@ -714,13 +711,12 @@ private static IList GetLockFileItems( foreach (var item in group.Items.NoAllocEnumerate()) { var newItem = new LockFileItem(item.Path); - object locale; - if (item.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.Locale, out locale)) + if (item.Properties.TryGetValue(ManagedCodeConventions.PropertyNames.Locale, out var locale)) { newItem.Properties[ManagedCodeConventions.PropertyNames.Locale] = (string)locale; } - object related; - if (item.Properties.TryGetValue("related", out related)) + + if (item.Properties.TryGetValue("related", out var related)) { newItem.Properties["related"] = (string)related; } @@ -915,13 +911,11 @@ private static List GetContentGroupsForFramework( foreach (var group in contentGroups) { - object keyObj; - if (group.Properties.TryGetValue(primaryKey, out keyObj)) + if (group.Properties.TryGetValue(primaryKey, out var keyObj)) { var key = (string)keyObj; - List index; - if (!primaryGroups.TryGetValue(key, out index)) + if (!primaryGroups.TryGetValue(key, out var index)) { index = new List(1); primaryGroups.Add(key, index); @@ -940,10 +934,9 @@ private static List GetContentGroupsForFramework( group => { // In the case of /native there is no TxM, here any should be used. - object frameworkObj; if (group.Properties.TryGetValue( - ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker, - out frameworkObj)) + ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker, + out var frameworkObj)) { return (NuGetFramework)frameworkObj; } diff --git a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs index 3416b53dbc3..ddc12831fe6 100644 --- a/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs +++ b/src/NuGet.Core/NuGet.Commands/RestoreCommand/Utility/MSBuildRestoreUtility.cs @@ -73,8 +73,7 @@ public static DependencyGraphSpec GetDependencySpec(IEnumerable it } else if (!string.IsNullOrEmpty(projectUniqueName)) { - List idItems; - if (!itemsById.TryGetValue(projectUniqueName, out idItems)) + if (!itemsById.TryGetValue(projectUniqueName, out var idItems)) { idItems = new List(1); itemsById.Add(projectUniqueName, idItems); @@ -583,8 +582,7 @@ private static void AddProjectReferences(PackageSpec spec, IEnumerable references; - if (aliasGroups.TryGetValue(framework, out references)) + if (aliasGroups.TryGetValue(framework, out var references)) { // Ensure unique if (!references.Any(e => comparer.Equals(e.ProjectUniqueName, frameworkPair.Item2.ProjectUniqueName))) diff --git a/src/NuGet.Core/NuGet.Common/UriUtility.cs b/src/NuGet.Core/NuGet.Common/UriUtility.cs index b8ba94c2e3b..9b5a19b9ade 100644 --- a/src/NuGet.Core/NuGet.Common/UriUtility.cs +++ b/src/NuGet.Core/NuGet.Common/UriUtility.cs @@ -31,8 +31,7 @@ public static Uri CreateSourceUri(string source, UriKind kind = UriKind.Absolute { source = FixSourceUri(source); - Uri? uri; - return Uri.TryCreate(source, kind, out uri) ? uri : null; + return Uri.TryCreate(source, kind, out var uri) ? uri : null; } private static string FixSourceUri(string source) @@ -75,8 +74,7 @@ public static string GetLocalPath(string localOrUriPath) && localOrUriPath.StartsWith(FilePrefix, StringComparison.OrdinalIgnoreCase)) { // convert to a uri and get the local path - Uri? uri; - if (Uri.TryCreate(localOrUriPath, UriKind.RelativeOrAbsolute, out uri)) + if (Uri.TryCreate(localOrUriPath, UriKind.RelativeOrAbsolute, out var uri)) { return uri.LocalPath; } diff --git a/src/NuGet.Core/NuGet.Configuration/PackageSource/PackageSourceProvider.cs b/src/NuGet.Core/NuGet.Configuration/PackageSource/PackageSourceProvider.cs index 23e2a6c0bc9..6d60f9b3374 100644 --- a/src/NuGet.Core/NuGet.Configuration/PackageSource/PackageSourceProvider.cs +++ b/src/NuGet.Core/NuGet.Configuration/PackageSource/PackageSourceProvider.cs @@ -778,12 +778,11 @@ internal void SavePackageSources(IEnumerable sources, IEnvironmen foreach (var source in sources) { AddItem? existingDisabledSourceItem = null; - SourceItem? existingSourceItem = null; CredentialsItem? existingCredentialsItem = null; var existingSourceIsEnabled = existingDisabledSourcesLookup == null || existingDisabledSourcesLookup.TryGetValue(source.Name, out existingDisabledSourceItem); - if (existingSettingsLookup.TryGetValue(source.Name, out existingSourceItem)) + if (existingSettingsLookup.TryGetValue(source.Name, out var existingSourceItem)) { var oldPackageSource = ReadPackageSource(existingSourceItem, existingSourceIsEnabled, Settings, environmentVariableReader); diff --git a/src/NuGet.Core/NuGet.Configuration/Proxy/ProxyCache.cs b/src/NuGet.Core/NuGet.Configuration/Proxy/ProxyCache.cs index 63898f13a8a..c9407bfa4a7 100644 --- a/src/NuGet.Core/NuGet.Configuration/Proxy/ProxyCache.cs +++ b/src/NuGet.Core/NuGet.Configuration/Proxy/ProxyCache.cs @@ -109,9 +109,8 @@ private bool TryAddProxyCredentialsToCache(WebProxy configuredProxy) // Next try reading from the environment variable http_proxy. This would be specified as http://:@proxy.com host = _environment.GetEnvironmentVariable(ConfigurationConstants.HostKey); - Uri? uri; if (!string.IsNullOrEmpty(host) - && Uri.TryCreate(host, UriKind.Absolute, out uri)) + && Uri.TryCreate(host, UriKind.Absolute, out var uri)) { var webProxy = new WebProxy(uri.GetComponents( UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped)); @@ -152,8 +151,7 @@ public void UpdateCredential(Uri proxyAddress, NetworkCredential credentials) public NetworkCredential? GetCredential(Uri proxyAddress, string authType) { - ICredentials? cachedCredentials; - if (_cachedCredentials.TryGetValue(proxyAddress, out cachedCredentials)) + if (_cachedCredentials.TryGetValue(proxyAddress, out var cachedCredentials)) { return cachedCredentials.GetCredential(proxyAddress, authType); } diff --git a/src/NuGet.Core/NuGet.Configuration/Settings/SettingFactory.cs b/src/NuGet.Core/NuGet.Configuration/Settings/SettingFactory.cs index 352879573fa..d6b008bf1a5 100644 --- a/src/NuGet.Core/NuGet.Configuration/Settings/SettingFactory.cs +++ b/src/NuGet.Core/NuGet.Configuration/Settings/SettingFactory.cs @@ -25,8 +25,7 @@ internal static SettingBase Parse(XNode node, SettingsFile origin) if (node is XElement element) { - var elementType = SettingElementType.Unknown; - Enum.TryParse(element.Name.LocalName, ignoreCase: true, result: out elementType); + Enum.TryParse(element.Name.LocalName, ignoreCase: true, result: out SettingElementType elementType); var parentType = SettingElementType.Unknown; if (element.Parent != null) diff --git a/src/NuGet.Core/NuGet.Credentials/PluginCredentialProvider.cs b/src/NuGet.Core/NuGet.Credentials/PluginCredentialProvider.cs index 079abf7cbb0..90528957baa 100644 --- a/src/NuGet.Core/NuGet.Credentials/PluginCredentialProvider.cs +++ b/src/NuGet.Core/NuGet.Credentials/PluginCredentialProvider.cs @@ -198,8 +198,7 @@ private PluginCredentialResponse GetPluginResponse(PluginCredentialRequest reque StandardErrorEncoding = Encoding.UTF8, }; - string stdOut = null; - var exitCode = Execute(startInfo, cancellationToken, out stdOut); + var exitCode = Execute(startInfo, cancellationToken, out var stdOut); var status = (PluginCredentialResponseExitCode)exitCode; diff --git a/src/NuGet.Core/NuGet.Credentials/PluginCredentialProviderBuilder.cs b/src/NuGet.Core/NuGet.Credentials/PluginCredentialProviderBuilder.cs index 8af79935936..0e9caff9a59 100644 --- a/src/NuGet.Core/NuGet.Credentials/PluginCredentialProviderBuilder.cs +++ b/src/NuGet.Core/NuGet.Credentials/PluginCredentialProviderBuilder.cs @@ -91,8 +91,7 @@ private int TimeoutSeconds var timeoutEnvar = _envarReader.GetEnvironmentVariable( CredentialsConstants.ProviderTimeoutSecondsEnvar); - int value; - if (int.TryParse(timeoutSetting, out value) + if (int.TryParse(timeoutSetting, out var value) || int.TryParse(timeoutEnvar, out value)) { return value; diff --git a/src/NuGet.Core/NuGet.Credentials/PreviewFeatureSettings.cs b/src/NuGet.Core/NuGet.Credentials/PreviewFeatureSettings.cs index d89d0e9b691..f60d93524fd 100644 --- a/src/NuGet.Core/NuGet.Credentials/PreviewFeatureSettings.cs +++ b/src/NuGet.Core/NuGet.Credentials/PreviewFeatureSettings.cs @@ -26,9 +26,8 @@ public const string DefaultCredentialsAfterCredentialProvidersEnvironmentVariabl private static bool GetFlagFromEnvironmentVariable(string variableName) { - bool flag; var flagString = environmentVariableReader.GetEnvironmentVariable(variableName); - return bool.TryParse(flagString, out flag) && flag; + return bool.TryParse(flagString, out var flag) && flag; } } } diff --git a/src/NuGet.Core/NuGet.DependencyResolver.Core/GraphModel/GraphOperations.cs b/src/NuGet.Core/NuGet.DependencyResolver.Core/GraphModel/GraphOperations.cs index cd5341edb61..e340b6f65eb 100644 --- a/src/NuGet.Core/NuGet.DependencyResolver.Core/GraphModel/GraphOperations.cs +++ b/src/NuGet.Core/NuGet.DependencyResolver.Core/GraphModel/GraphOperations.cs @@ -417,8 +417,7 @@ private static void WalkTreeDectectConflicts(GraphNode node, Confl for (var i = 0; i < count; i++) { var childNode = innerNodes[i]; - GraphNode acceptedNode; - if (acceptedLibraries.TryGetValue(childNode.Key.Name, out acceptedNode) && + if (acceptedLibraries.TryGetValue(childNode.Key.Name, out var acceptedNode) && childNode != acceptedNode && childNode.Key.VersionRange != null && acceptedNode.Item.Key.Version != null) diff --git a/src/NuGet.Core/NuGet.Frameworks/FrameworkNameProvider.cs b/src/NuGet.Core/NuGet.Frameworks/FrameworkNameProvider.cs index 27e91bc565e..b2d6050c419 100644 --- a/src/NuGet.Core/NuGet.Frameworks/FrameworkNameProvider.cs +++ b/src/NuGet.Core/NuGet.Frameworks/FrameworkNameProvider.cs @@ -549,8 +549,7 @@ public bool TryGetPortableProfileNumber(string profile, out int profileNumber) public bool TryGetPortableFrameworks(string profile, bool includeOptional, [NotNullWhen(true)] out IEnumerable? frameworks) { // attempt to parse the profile for a number - int profileNum; - if (TryGetPortableProfileNumber(profile, out profileNum)) + if (TryGetPortableProfileNumber(profile, out var profileNum)) { if (TryGetPortableFrameworks(profileNum, includeOptional, out frameworks)) { @@ -1037,14 +1036,12 @@ private static int CompareUsingPrecedence(NuGetFramework? x, NuGetFramework? y, return 0; } - int xIndex; - if (!precedence.TryGetValue(x.Framework, out xIndex)) + if (!precedence.TryGetValue(x.Framework, out var xIndex)) { xIndex = int.MaxValue; } - int yIndex; - if (!precedence.TryGetValue(y.Framework, out yIndex)) + if (!precedence.TryGetValue(y.Framework, out var yIndex)) { yIndex = int.MaxValue; } diff --git a/src/NuGet.Core/NuGet.Frameworks/NuGetFrameworkFactory.cs b/src/NuGet.Core/NuGet.Frameworks/NuGetFrameworkFactory.cs index 1b4506ae174..211e8b09e47 100644 --- a/src/NuGet.Core/NuGet.Frameworks/NuGetFrameworkFactory.cs +++ b/src/NuGet.Core/NuGet.Frameworks/NuGetFrameworkFactory.cs @@ -75,21 +75,16 @@ internal static NuGetFramework ParseComponents(string targetFrameworkMoniker, st if (string.IsNullOrEmpty(targetFrameworkMoniker)) throw new ArgumentException(Strings.ArgumentCannotBeNullOrEmpty, nameof(targetFrameworkMoniker)); if (mappings == null) throw new ArgumentNullException(nameof(mappings)); - NuGetFramework? result; - string targetFrameworkIdentifier; - Version targetFrameworkVersion; var parts = GetParts(targetFrameworkMoniker); // if the first part is a special framework, ignore the rest - if (TryParseSpecialFramework(parts[0], out result)) + if (TryParseSpecialFramework(parts[0], out var result)) { return result; } - string? profile; - string? targetFrameworkProfile; - ParseFrameworkNameParts(mappings, parts, out targetFrameworkIdentifier, out targetFrameworkVersion, out targetFrameworkProfile); - if (!mappings.TryGetProfile(targetFrameworkIdentifier, targetFrameworkProfile ?? string.Empty, out profile)) + ParseFrameworkNameParts(mappings, parts, out var targetFrameworkIdentifier, out var targetFrameworkVersion, out var targetFrameworkProfile); + if (!mappings.TryGetProfile(targetFrameworkIdentifier, targetFrameworkProfile ?? string.Empty, out var profile)) { profile = targetFrameworkProfile; } @@ -123,9 +118,7 @@ internal static NuGetFramework ParseComponents(string targetFrameworkMoniker, st if (!string.IsNullOrEmpty(targetPlatformMoniker) && isNet5EraTfm) { - string targetPlatformIdentifier; - Version platformVersion; - ParsePlatformParts(GetParts(targetPlatformMoniker!), out targetPlatformIdentifier, out platformVersion); + ParsePlatformParts(GetParts(targetPlatformMoniker!), out var targetPlatformIdentifier, out var platformVersion); result = new NuGetFramework(targetFrameworkIdentifier, targetFrameworkVersion, targetPlatformIdentifier ?? string.Empty, platformVersion); } else @@ -268,9 +261,8 @@ public static NuGetFramework ParseFolder(string folderName, IFrameworkNameProvid folderName = Uri.UnescapeDataString(folderName); } - NuGetFramework? result; // first check if we have a special or common framework - if (!TryParseSpecialFramework(folderName, out result) + if (!TryParseSpecialFramework(folderName, out var result) && !TryParseCommonFramework(folderName, out result)) { // assume this is unsupported unless we find a match @@ -341,8 +333,7 @@ public static NuGetFramework ParseFolder(string folderName, IFrameworkNameProvid } else { - var profileNumber = -1; - if (mappings.TryGetPortableProfile(clientFrameworks, out profileNumber)) + if (mappings.TryGetPortableProfile(clientFrameworks, out var profileNumber)) { var portableProfileNumber = FrameworkNameHelpers.GetPortableProfileNumberString(profileNumber); result = new NuGetFramework(framework, version, portableProfileNumber); diff --git a/src/NuGet.Core/NuGet.LibraryModel/LibraryExtensions.cs b/src/NuGet.Core/NuGet.LibraryModel/LibraryExtensions.cs index 34a3dedd247..ba2f3fa4f4f 100644 --- a/src/NuGet.Core/NuGet.LibraryModel/LibraryExtensions.cs +++ b/src/NuGet.Core/NuGet.LibraryModel/LibraryExtensions.cs @@ -18,8 +18,7 @@ public static bool IsEclipsedBy(this LibraryRange library, LibraryRange other) public static T? GetItem(this Library library, string key) { - object? value; - if (library.Items.TryGetValue(key, out value)) + if (library.Items.TryGetValue(key, out var value)) { return (T)value; } @@ -28,8 +27,7 @@ public static bool IsEclipsedBy(this LibraryRange library, LibraryRange other) public static T GetRequiredItem(this Library library, string key) { - object? value; - if (library.Items.TryGetValue(key, out value)) + if (library.Items.TryGetValue(key, out var value)) { return (T)value; } diff --git a/src/NuGet.Core/NuGet.LibraryModel/LibraryType.cs b/src/NuGet.Core/NuGet.LibraryModel/LibraryType.cs index 2644fdb6daf..06fb8831807 100644 --- a/src/NuGet.Core/NuGet.LibraryModel/LibraryType.cs +++ b/src/NuGet.Core/NuGet.LibraryModel/LibraryType.cs @@ -57,8 +57,7 @@ private LibraryType(string value, bool isKnown) public static LibraryType Parse(string value) { - LibraryType action; - if (_knownLibraryTypes.TryGetValue(value, out action)) + if (_knownLibraryTypes.TryGetValue(value, out var action)) { return action; } diff --git a/src/NuGet.Core/NuGet.PackageManagement/IDE/PackageRestoreManager.cs b/src/NuGet.Core/NuGet.PackageManagement/IDE/PackageRestoreManager.cs index 1036828ed12..0b7e974209e 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/IDE/PackageRestoreManager.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/IDE/PackageRestoreManager.cs @@ -161,8 +161,7 @@ private async Task>> GetPackagesRefere var installedPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); foreach (var installedPackageReference in installedPackageReferences) { - List projectNames = null; - if (!packageReferencesDict.TryGetValue(installedPackageReference, out projectNames)) + if (!packageReferencesDict.TryGetValue(installedPackageReference, out var projectNames)) { projectNames = new List(); packageReferencesDict.Add(installedPackageReference, projectNames); @@ -532,11 +531,9 @@ private static async Task> PackageRestoreRunnerAsync( INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext) { - PackageReference currentPackageReference = null; - var attemptedPackages = new List(); - while (packageReferencesQueue.TryDequeue(out currentPackageReference)) + while (packageReferencesQueue.TryDequeue(out var currentPackageReference)) { var attemptedPackage = await RestorePackageAsync( currentPackageReference, @@ -642,8 +639,7 @@ private static async Task CopySatelliteFilesRunnerAsync(ConcurrentQueue e.RestoreMetadata.ProjectUniqueName)) { - BuildIntegratedNuGetProject project; - if (projectUniqueNamesForBuildIntToUpdate.TryGetValue(projectUniqueName, out project)) + if (projectUniqueNamesForBuildIntToUpdate.TryGetValue(projectUniqueName, out var project)) { sortedProjectsToUpdate.Add(project); } @@ -2591,8 +2590,7 @@ await ExecuteBuildIntegratedProjectActionsAsync(buildIntegratedProject, // raise Nuget batch start event var batchId = Guid.NewGuid().ToString(); - string name; - nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.Name, out name); + nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.Name, out string name); var projectPath = msbuildProject?.MSBuildProjectPath; packageProjectEventArgs = new PackageProjectEventArgs(batchId, name, projectPath); BatchStart?.Invoke(this, packageProjectEventArgs); @@ -3798,8 +3796,7 @@ public static Task GetLatestVersionAsync( Common.ILogger log, CancellationToken token) { - NuGetFramework framework; - if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out framework)) + if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out var framework)) { // Default to the any framework if the project does not specify a framework. framework = NuGetFramework.AnyFramework; @@ -3824,8 +3821,7 @@ public static async Task GetLatestVersionAsync( { var tasks = new List>(); - NuGetFramework framework; - if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out framework)) + if (!project.TryGetMetadata(NuGetProjectMetadataKeys.TargetFramework, out var framework)) { // Default to the any framework if the project does not specify a framework. framework = NuGetFramework.AnyFramework; diff --git a/src/NuGet.Core/NuGet.PackageManagement/PackageRestoreConsent.cs b/src/NuGet.Core/NuGet.PackageManagement/PackageRestoreConsent.cs index 241384dd403..9ca90b757bd 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/PackageRestoreConsent.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/PackageRestoreConsent.cs @@ -90,11 +90,8 @@ private static bool IsSet(string value, bool defaultValue) value = value.Trim(); - bool boolResult; - int intResult; - - var result = ((bool.TryParse(value, out boolResult) && boolResult) || - (int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out intResult) && (intResult == 1))); + var result = ((bool.TryParse(value, out var boolResult) && boolResult) || + (int.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out var intResult) && (intResult == 1))); return result; } 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/Projects/NuGetProject.cs b/src/NuGet.Core/NuGet.PackageManagement/Projects/NuGetProject.cs index df7b4c12366..87b85c6383e 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Projects/NuGetProject.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Projects/NuGetProject.cs @@ -82,8 +82,7 @@ public bool TryGetMetadata(string key, out T value) { value = default(T); - object oValue; - if (Metadata.TryGetValue(key, out oValue)) + if (Metadata.TryGetValue(key, out var oValue)) { if (oValue == null) { @@ -133,8 +132,7 @@ public static string GetUniqueNameOrName(NuGetProject nuGetProject) throw new ArgumentNullException(nameof(nuGetProject)); } - string nuGetProjectName; - if (!nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.UniqueName, out nuGetProjectName)) + if (!nuGetProject.TryGetMetadata(NuGetProjectMetadataKeys.UniqueName, out string nuGetProjectName)) { // Unique name is not set, simply return the name nuGetProjectName = nuGetProject.GetMetadata(NuGetProjectMetadataKeys.Name); diff --git a/src/NuGet.Core/NuGet.PackageManagement/Projects/ProjectJsonNuGetProject.cs b/src/NuGet.Core/NuGet.PackageManagement/Projects/ProjectJsonNuGetProject.cs index aef27747d33..0d2f4f1d506 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Projects/ProjectJsonNuGetProject.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Projects/ProjectJsonNuGetProject.cs @@ -169,8 +169,7 @@ public override async Task> GetPackageSpecsAsync(Depe public override async Task<(IReadOnlyList dgSpecs, IReadOnlyList additionalMessages)> GetPackageSpecsAndAdditionalMessagesAsync(DependencyGraphCacheContext context) { - PackageSpec packageSpec = null; - if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out packageSpec)) + if (context == null || !context.PackageSpecCache.TryGetValue(MSBuildProjectPath, out var packageSpec)) { packageSpec = JsonPackageSpecReader.GetPackageSpec(ProjectName, JsonConfigPath); if (packageSpec == null) diff --git a/src/NuGet.Core/NuGet.PackageManagement/Resolution/GatherCache.cs b/src/NuGet.Core/NuGet.PackageManagement/Resolution/GatherCache.cs index a73dd8a7cdb..19d851e5ac8 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Resolution/GatherCache.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Resolution/GatherCache.cs @@ -66,9 +66,7 @@ public GatherCacheResult GetPackage( var hasEntry = false; - SourcePackageDependencyInfo result; - - hasEntry = _singleVersion.TryGetValue(key, out result); + hasEntry = _singleVersion.TryGetValue(key, out var result); if (!hasEntry) { @@ -107,9 +105,7 @@ public GatherCacheResult GetPackages( { var key = new GatherAllCacheKey(packageId, source, framework); - List result; - - var hasEntry = _allPackageVersions.TryGetValue(key, out result); + var hasEntry = _allPackageVersions.TryGetValue(key, out var result); return new GatherCacheResult(hasEntry, result); } diff --git a/src/NuGet.Core/NuGet.PackageManagement/Resolution/PrunePackageTree.cs b/src/NuGet.Core/NuGet.PackageManagement/Resolution/PrunePackageTree.cs index b3fd4f120cd..c2d0f289e76 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Resolution/PrunePackageTree.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Resolution/PrunePackageTree.cs @@ -83,8 +83,7 @@ private static void WalkDependencies(IDictionary> GetPackageD if (dependencyPackageIdentity != null) { // Update the package dependents dictionary - HashSet dependents; - if (!dependentsDict.TryGetValue(dependencyPackageIdentity, out dependents)) + if (!dependentsDict.TryGetValue(dependencyPackageIdentity, out var dependents)) { dependentsDict[dependencyPackageIdentity] = dependents = new HashSet(PackageIdentity.Comparer); } dependents.Add(packageIdentity); // Update the package dependencies dictionary - HashSet dependencies; - if (!dependenciesDict.TryGetValue(packageIdentity, out dependencies)) + if (!dependenciesDict.TryGetValue(packageIdentity, out var dependencies)) { dependenciesDict[packageIdentity] = dependencies = new HashSet(PackageIdentity.Comparer); } @@ -51,8 +49,7 @@ public static IDictionary> GetPackageD public static ICollection GetPackagesToBeUninstalled(PackageIdentity packageIdentity, IEnumerable dependencyInfoEnumerable, IEnumerable installedPackages, UninstallationContext uninstallationContext) { - IDictionary> dependenciesDictionary; - var dependentsDictionary = GetPackageDependents(dependencyInfoEnumerable, installedPackages, out dependenciesDictionary); + var dependentsDictionary = GetPackageDependents(dependencyInfoEnumerable, installedPackages, out var dependenciesDictionary); var packagesMarkedForUninstall = MarkPackagesToBeUninstalled(packageIdentity, dependenciesDictionary, uninstallationContext); @@ -66,8 +63,7 @@ private static void CheckIfPackageCanBeUninstalled(PackageIdentity packageIdenti UninstallationContext uninstallationContext, HashSet packagesMarkedForUninstall) { - HashSet dependents; - if (dependentsDict.TryGetValue(packageIdentity, out dependents) + if (dependentsDict.TryGetValue(packageIdentity, out var dependents) && dependents != null) { if (!uninstallationContext.ForceRemove) @@ -80,9 +76,8 @@ private static void CheckIfPackageCanBeUninstalled(PackageIdentity packageIdenti } } - HashSet dependencies; if (uninstallationContext.RemoveDependencies - && dependenciesDict.TryGetValue(packageIdentity, out dependencies) + && dependenciesDict.TryGetValue(packageIdentity, out var dependencies) && dependencies != null) { foreach (var dependency in dependencies) @@ -110,9 +105,8 @@ private static HashSet MarkPackagesToBeUninstalled(PackageIdent var headPackage = breathFirstSearchQueue.Dequeue(); markedPackages.Add(headPackage); - HashSet dependencies; if (uninstallationContext.RemoveDependencies - && dependenciesDict.TryGetValue(headPackage, out dependencies) + && dependenciesDict.TryGetValue(headPackage, out var dependencies) && dependencies != null) { foreach (var dependency in dependencies) 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/MSBuildNuGetProjectSystemUtility.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs index 7397bd2a80d..34dce137314 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/MSBuildNuGetProjectSystemUtility.cs @@ -170,10 +170,9 @@ internal static async Task AddFilesAsync( var effectivePathForContentFile = GetEffectivePathForContentFile(packageTargetFramework, file); // Resolve the target path - IPackageFileTransformer installTransformer; var path = ResolveTargetPath(projectSystem, fileTransformers, - fte => fte.InstallExtension, effectivePathForContentFile, out installTransformer); + fte => fte.InstallExtension, effectivePathForContentFile, out var installTransformer); if (projectSystem.IsSupportedFile(path)) { @@ -517,11 +516,9 @@ private static string ResolvePath( Func extensionSelector, string effectivePath) { - string truncatedPath; - // Remove the transformer extension (e.g. .pp, .transform) var transformer = FindFileTransformer( - fileTransformers, extensionSelector, effectivePath, out truncatedPath); + fileTransformers, extensionSelector, effectivePath, out var truncatedPath); if (transformer != null) { @@ -538,10 +535,8 @@ private static string ResolveTargetPath( string effectivePath, out IPackageFileTransformer transformer) { - string truncatedPath; - // Remove the transformer extension (e.g. .pp, .transform) - transformer = FindFileTransformer(fileTransformers, extensionSelector, effectivePath, out truncatedPath); + transformer = FindFileTransformer(fileTransformers, extensionSelector, effectivePath, out var truncatedPath); if (transformer != null) { effectivePath = truncatedPath; diff --git a/src/NuGet.Core/NuGet.PackageManagement/Utility/UriHelper.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/UriHelper.cs index 8c97c199f4f..2dd5442b150 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/UriHelper.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/UriHelper.cs @@ -55,8 +55,7 @@ public static bool IsHttpSource(string source) return false; } - Uri uri; - if (Uri.TryCreate(source, UriKind.Absolute, out uri)) + if (Uri.TryCreate(source, UriKind.Absolute, out var uri)) { return IsHttpUrl(uri); } @@ -121,8 +120,7 @@ private static bool IsHttpUrl(Uri uri) private static bool IsLocal(string currentSource) { - Uri currentURI; - if (Uri.TryCreate(currentSource, UriKind.RelativeOrAbsolute, out currentURI)) + if (Uri.TryCreate(currentSource, UriKind.RelativeOrAbsolute, out var currentURI)) { if (currentURI.IsFile) { @@ -137,8 +135,7 @@ private static bool IsLocal(string currentSource) private static bool IsUNC(string currentSource) { - Uri currentURI; - if (Uri.TryCreate(currentSource, UriKind.RelativeOrAbsolute, out currentURI)) + if (Uri.TryCreate(currentSource, UriKind.RelativeOrAbsolute, out var currentURI)) { if (currentURI.IsUnc) { diff --git a/src/NuGet.Core/NuGet.PackageManagement/Utility/XElementExtensions.cs b/src/NuGet.Core/NuGet.PackageManagement/Utility/XElementExtensions.cs index f4d8f054799..9c5602372f2 100644 --- a/src/NuGet.Core/NuGet.PackageManagement/Utility/XElementExtensions.cs +++ b/src/NuGet.Core/NuGet.PackageManagement/Utility/XElementExtensions.cs @@ -156,9 +156,8 @@ public static XElement MergeWith(this XElement source, XElement target, IDiction } else { - Action nodeAction; if (nodeActions != null - && nodeActions.TryGetValue(targetChild.Name, out nodeAction)) + && nodeActions.TryGetValue(targetChild.Name, out var nodeAction)) { nodeAction(source, targetChild); } @@ -234,9 +233,8 @@ private static bool HasConflict(XElement source, XElement target) // Loop over all the other attributes and see if there are foreach (var targetAttr in target.Attributes()) { - string sourceValue; // if any of the attributes are in the source (names match) but the value doesn't match then we've found a conflict - if (sourceAttr.TryGetValue(targetAttr.Name, out sourceValue) + if (sourceAttr.TryGetValue(targetAttr.Name, out var sourceValue) && sourceValue != targetAttr.Value) { return true; diff --git a/src/NuGet.Core/NuGet.Packaging/ContentModel/ContentItemCollection.cs b/src/NuGet.Core/NuGet.Packaging/ContentModel/ContentItemCollection.cs index 424616378b1..47853b0eb21 100644 --- a/src/NuGet.Core/NuGet.Packaging/ContentModel/ContentItemCollection.cs +++ b/src/NuGet.Core/NuGet.Packaging/ContentModel/ContentItemCollection.cs @@ -223,14 +223,13 @@ public bool HasItemGroup(SelectionCriteria criteria, params PatternSet[] definit } else { - object? itemProperty; - if (!itemGroup.Properties.TryGetValue(criteriaProperty.Key, out itemProperty)) + if (!itemGroup.Properties.TryGetValue(criteriaProperty.Key, out var itemProperty)) { groupIsValid = false; break; } - ContentPropertyDefinition? propertyDefinition; - if (!definition.PropertyDefinitions.TryGetValue(criteriaProperty.Key, out propertyDefinition)) + + if (!definition.PropertyDefinitions.TryGetValue(criteriaProperty.Key, out var propertyDefinition)) { groupIsValid = false; break; @@ -507,8 +506,7 @@ public bool Equals(ContentItem? x, ContentItem? y) { foreach (var xProperty in x._properties) { - object? yValue; - if (!y._properties.TryGetValue(xProperty.Key, out yValue)) + if (!y._properties.TryGetValue(xProperty.Key, out var yValue)) { return false; } diff --git a/src/NuGet.Core/NuGet.Packaging/ContentModel/Infrastructure/Parser.cs b/src/NuGet.Core/NuGet.Packaging/ContentModel/Infrastructure/Parser.cs index 37b064612a8..0f539f312c2 100644 --- a/src/NuGet.Core/NuGet.Packaging/ContentModel/Infrastructure/Parser.cs +++ b/src/NuGet.Core/NuGet.Packaging/ContentModel/Infrastructure/Parser.cs @@ -70,8 +70,7 @@ internal ContentItem Match(string path, IReadOnlyDictionary substring = path.AsMemory(startIndex, delimiterIndex - startIndex); - object value; - if (propertyDefinition.TryLookup(substring, _table, _matchOnly, out value)) + if (propertyDefinition.TryLookup(substring, _table, _matchOnly, out var value)) { if (!_matchOnly) { diff --git a/src/NuGet.Core/NuGet.Packaging/ContentModel/ManagedCodeConventions.cs b/src/NuGet.Core/NuGet.Packaging/ContentModel/ManagedCodeConventions.cs index 58d3a718549..12d2684e38d 100644 --- a/src/NuGet.Core/NuGet.Packaging/ContentModel/ManagedCodeConventions.cs +++ b/src/NuGet.Core/NuGet.Packaging/ContentModel/ManagedCodeConventions.cs @@ -131,8 +131,7 @@ private static object CodeLanguage_Parser(ReadOnlyMemory name, PatternTabl { if (table != null) { - object val; - if (table.TryLookup(PropertyNames.CodeLanguage, name, out val)) + if (table.TryLookup(PropertyNames.CodeLanguage, name, out var val)) { return val; } @@ -164,8 +163,7 @@ internal static object Locale_Parser(ReadOnlyMemory name, PatternTable tab { if (table != null) { - object val; - if (table.TryLookup(PropertyNames.Locale, name, out val)) + if (table.TryLookup(PropertyNames.Locale, name, out var val)) { return val; } @@ -214,12 +212,10 @@ private object TargetFrameworkName_Parser( PatternTable table, bool matchOnly) { - object obj = null; - // Check for replacements if (table != null) { - if (table.TryLookup(PropertyNames.TargetFrameworkMoniker, name, out obj)) + if (table.TryLookup(PropertyNames.TargetFrameworkMoniker, name, out var obj)) { return obj; } @@ -228,8 +224,7 @@ private object TargetFrameworkName_Parser( // Check the cache for an exact match if (!name.IsEmpty) { - NuGetFramework cachedResult; - if (!_frameworkCache.TryGetValue(name, out cachedResult)) + if (!_frameworkCache.TryGetValue(name, out var cachedResult)) { // Parse and add the framework to the cache cachedResult = TargetFrameworkName_ParserCore(name.ToString()); diff --git a/src/NuGet.Core/NuGet.Packaging/ContentModel/PatternTable.cs b/src/NuGet.Core/NuGet.Packaging/ContentModel/PatternTable.cs index 73c8b192bf9..d77a2ee11c7 100644 --- a/src/NuGet.Core/NuGet.Packaging/ContentModel/PatternTable.cs +++ b/src/NuGet.Core/NuGet.Packaging/ContentModel/PatternTable.cs @@ -31,8 +31,7 @@ public PatternTable(IEnumerable entries) foreach (var entry in entries) { - Dictionary, object> byProp; - if (!_table.TryGetValue(entry.PropertyName, out byProp)) + if (!_table.TryGetValue(entry.PropertyName, out var byProp)) { byProp = new Dictionary, object>(ReadOnlyMemoryCharComparerOrdinal.Instance); _table.Add(entry.PropertyName, byProp); @@ -56,8 +55,7 @@ internal bool TryLookup(string propertyName, ReadOnlyMemory name, out obje } Debug.Assert(MemoryMarshal.TryGetString(name, out _, out _, out _)); - Dictionary, object> byProp; - if (_table.TryGetValue(propertyName, out byProp)) + if (_table.TryGetValue(propertyName, out var byProp)) { return byProp.TryGetValue(name, out value); } diff --git a/src/NuGet.Core/NuGet.Packaging/ContentModel/SelectionCriteriaBuilder.cs b/src/NuGet.Core/NuGet.Packaging/ContentModel/SelectionCriteriaBuilder.cs index 2042e557c60..e6b8688a275 100644 --- a/src/NuGet.Core/NuGet.Packaging/ContentModel/SelectionCriteriaBuilder.cs +++ b/src/NuGet.Core/NuGet.Packaging/ContentModel/SelectionCriteriaBuilder.cs @@ -44,8 +44,7 @@ internal SelectionCriteriaEntryBuilder(SelectionCriteriaBuilder builder, Selecti { get { - ContentPropertyDefinition propertyDefinition; - if (!Builder.Properties.TryGetValue(key, out propertyDefinition)) + if (!Builder.Properties.TryGetValue(key, out var propertyDefinition)) { throw new Exception("Undefined property used for criteria"); } @@ -55,8 +54,7 @@ internal SelectionCriteriaEntryBuilder(SelectionCriteriaBuilder builder, Selecti } else { - object valueLookup; - if (propertyDefinition.TryLookup(value.AsMemory(), table: null, matchOnly: false, value: out valueLookup)) + if (propertyDefinition.TryLookup(value.AsMemory(), table: null, matchOnly: false, value: out var valueLookup)) { Entry.Properties[key] = valueLookup; } diff --git a/src/NuGet.Core/NuGet.Packaging/Core/NuspecCoreReaderBase.cs b/src/NuGet.Core/NuGet.Packaging/Core/NuspecCoreReaderBase.cs index 8ef2906273b..d93995700fb 100644 --- a/src/NuGet.Core/NuGet.Packaging/Core/NuspecCoreReaderBase.cs +++ b/src/NuGet.Core/NuGet.Packaging/Core/NuspecCoreReaderBase.cs @@ -142,8 +142,7 @@ public virtual IEnumerable> GetMetadata() /// public virtual string GetMetadataValue(string name) { - string metadataValue; - MetadataValues.TryGetValue(name, out metadataValue); + MetadataValues.TryGetValue(name, out var metadataValue); return metadataValue ?? string.Empty; } diff --git a/src/NuGet.Core/NuGet.Packaging/MinClientVersionUtility.cs b/src/NuGet.Core/NuGet.Packaging/MinClientVersionUtility.cs index e44a2591dd8..e62aaaa150c 100644 --- a/src/NuGet.Core/NuGet.Packaging/MinClientVersionUtility.cs +++ b/src/NuGet.Core/NuGet.Packaging/MinClientVersionUtility.cs @@ -81,8 +81,7 @@ public static NuGetVersion GetNuGetClientVersion() { var versionString = ClientVersionUtility.GetNuGetAssemblyVersion(); - NuGetVersion clientVersion; - if (!NuGetVersion.TryParse(versionString, out clientVersion)) + if (!NuGetVersion.TryParse(versionString, out var clientVersion)) { throw new InvalidOperationException(Strings.UnableToParseClientVersion); } diff --git a/src/NuGet.Core/NuGet.Packaging/NuspecReader.cs b/src/NuGet.Core/NuGet.Packaging/NuspecReader.cs index cb7dc197b0f..8e7579bebf8 100644 --- a/src/NuGet.Core/NuGet.Packaging/NuspecReader.cs +++ b/src/NuGet.Core/NuGet.Packaging/NuspecReader.cs @@ -242,8 +242,7 @@ public IEnumerable GetFrameworkAssemblyGroups() // apply items to each framework foreach (var framework in frameworks) { - HashSet items = null; - if (!groups.TryGetValue(framework, out items)) + if (!groups.TryGetValue(framework, out var items)) { items = new HashSet(StringComparer.OrdinalIgnoreCase); groups.Add(framework, items); diff --git a/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PackageBuilder.cs b/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PackageBuilder.cs index 1e053021f1a..c26028338a1 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PackageBuilder.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PackageBuilder.cs @@ -1129,8 +1129,7 @@ public void AddFiles(string basePath, string source, string destination, string internal static IEnumerable ResolveSearchPattern(string basePath, string searchPath, string targetPath, bool includeEmptyDirectories) { - string normalizedBasePath; - IEnumerable searchResults = PathResolver.PerformWildcardSearch(basePath, searchPath, includeEmptyDirectories, out normalizedBasePath); + IEnumerable searchResults = PathResolver.PerformWildcardSearch(basePath, searchPath, includeEmptyDirectories, out var normalizedBasePath); return searchResults.Select(result => result.IsFile diff --git a/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PhysicalPackageFile.cs b/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PhysicalPackageFile.cs index 571cf4bf388..eeb13cf886a 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PhysicalPackageFile.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/PhysicalPackageFile.cs @@ -51,8 +51,7 @@ public string TargetPath if (string.Compare(_targetPath, value, StringComparison.OrdinalIgnoreCase) != 0) { _targetPath = value; - string effectivePath; - _nugetFramework = FrameworkNameUtility.ParseNuGetFrameworkFromFilePath(_targetPath, out effectivePath); + _nugetFramework = FrameworkNameUtility.ParseNuGetFrameworkFromFilePath(_targetPath, out var effectivePath); if (_nugetFramework != null && _nugetFramework.Version.Major < 5) { _targetFramework = new FrameworkName(_nugetFramework.DotNetFrameworkName); diff --git a/src/NuGet.Core/NuGet.Packaging/PackageCreation/Extensions/XElementExtensions.cs b/src/NuGet.Core/NuGet.Packaging/PackageCreation/Extensions/XElementExtensions.cs index 41c5ee70f3c..fc76524c78e 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageCreation/Extensions/XElementExtensions.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageCreation/Extensions/XElementExtensions.cs @@ -130,9 +130,8 @@ private static bool HasConflict(XElement source, XElement target) // Loop over all the other attributes and see if there are foreach (var targetAttr in target.Attributes()) { - string sourceValue; // if any of the attributes are in the source (names match) but the value doesn't match then we've found a conflict - if (sourceAttr.TryGetValue(targetAttr.Name, out sourceValue) + if (sourceAttr.TryGetValue(targetAttr.Name, out var sourceValue) && sourceValue != targetAttr.Value) { return true; diff --git a/src/NuGet.Core/NuGet.Packaging/PackageExtraction/PackagePathHelper.cs b/src/NuGet.Core/NuGet.Packaging/PackageExtraction/PackagePathHelper.cs index 3d7e79b3b6d..dd215e9f39b 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageExtraction/PackagePathHelper.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageExtraction/PackagePathHelper.cs @@ -92,12 +92,11 @@ private static bool FileNameMatchesPattern(PackageIdentity packageIdentity, stri { var packageId = packageIdentity.Id; var name = Path.GetFileNameWithoutExtension(path); - NuGetVersion parsedVersion; // When matching by pattern, we will always have a version token. Packages without versions would be matched early on by the version-less path resolver // when doing an exact match. return name.Length > packageId.Length && - NuGetVersion.TryParse(name.Substring(packageId.Length + 1), out parsedVersion) && + NuGetVersion.TryParse(name.Substring(packageId.Length + 1), out var parsedVersion) && parsedVersion.Equals(packageIdentity.Version); } diff --git a/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs b/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs index a4b1bb7e959..eb6a4b5fbce 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackageReaderBase.cs @@ -432,8 +432,7 @@ protected IEnumerable GetFileGroups(string folder) // Use the known framework or if the folder did not parse, use the Any framework and consider it a sub folder var framework = GetFrameworkFromPath(path, allowSubFolders); - List items = null; - if (!groups.TryGetValue(framework, out items)) + if (!groups.TryGetValue(framework, out var items)) { items = new List(); groups.Add(framework, items); diff --git a/src/NuGet.Core/NuGet.Packaging/PackagesConfig.cs b/src/NuGet.Core/NuGet.Packaging/PackagesConfig.cs index 928502af083..090ee50d3f2 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackagesConfig.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackagesConfig.cs @@ -43,8 +43,7 @@ public static bool HasAttributeValue(XElement node, string attributeName, string { foreach (var package in node.Elements(XName.Get(PackageNodeName))) { - string value; - bool hasValue = TryGetAttribute(package, attributeName, out value); + bool hasValue = TryGetAttribute(package, attributeName, out var value); if (hasValue && string.Equals(targetValue, value, StringComparison.OrdinalIgnoreCase)) { element = package; @@ -61,8 +60,7 @@ public static bool HasAttributeValue(XElement node, string attributeName, string /// public static bool BoolAttribute(XElement node, string name, bool defaultValue = false) { - string value = null; - if (PackagesConfig.TryGetAttribute(node, name, out value)) + if (PackagesConfig.TryGetAttribute(node, name, out var value)) { if (StringComparer.OrdinalIgnoreCase.Equals(value, "true")) { diff --git a/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs b/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs index 16c54985011..d068ff2c5e4 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackagesConfigReader.cs @@ -142,8 +142,7 @@ public IEnumerable GetPackages(bool allowDuplicatePackageIds) foreach (var package in _doc.Root.Elements(XName.Get(PackagesConfig.PackageNodeName))) { - string id = null; - if (!PackagesConfig.TryGetAttribute(package, "id", out id) + if (!PackagesConfig.TryGetAttribute(package, "id", out var id) || String.IsNullOrEmpty(id)) { throw new PackagesConfigReaderException(string.Format( @@ -151,8 +150,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 +160,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 +169,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/PackagesConfigWriter.cs b/src/NuGet.Core/NuGet.Packaging/PackagesConfigWriter.cs index d16b48efff5..922270edf6a 100644 --- a/src/NuGet.Core/NuGet.Packaging/PackagesConfigWriter.cs +++ b/src/NuGet.Core/NuGet.Packaging/PackagesConfigWriter.cs @@ -266,13 +266,11 @@ public void UpdateOrAddPackageEntry(XDocument originalConfig, PackageReference n var originalPackagesNode = originalConfig.Element(XName.Get(PackagesConfig.PackagesNodeName)); - XElement matchingIdNode; - if (PackagesConfig.HasAttributeValue( - originalPackagesNode, - PackagesConfig.IdAttributeName, - newEntry.PackageIdentity.Id, - out matchingIdNode)) + originalPackagesNode, + PackagesConfig.IdAttributeName, + newEntry.PackageIdentity.Id, + out var matchingIdNode)) { // Find the old entry and update it based on the new entry var packagesNode = _xDocument.Element(XName.Get(PackagesConfig.PackagesNodeName)); @@ -418,19 +416,16 @@ private XElement EnsurePackagesNode() private XElement FindMatchingPackageNode(PackageReference entry, XElement packagesNode) { - XElement matchingIdNode; bool hasMatchingNode = PackagesConfig.HasAttributeValue(packagesNode, PackagesConfig.IdAttributeName, - entry.PackageIdentity.Id, out matchingIdNode); + entry.PackageIdentity.Id, out var matchingIdNode); if (matchingIdNode != null) { - string version; - PackagesConfig.TryGetAttribute(matchingIdNode, PackagesConfig.VersionAttributeName, out version); + PackagesConfig.TryGetAttribute(matchingIdNode, PackagesConfig.VersionAttributeName, out var version); if (!string.IsNullOrEmpty(version)) { - NuGetVersion nuGetVersion; - bool isNuGetVersion = NuGetVersion.TryParse(version, out nuGetVersion); + bool isNuGetVersion = NuGetVersion.TryParse(version, out var nuGetVersion); if (isNuGetVersion && nuGetVersion != null && nuGetVersion.Equals(entry.PackageIdentity.Version)) { @@ -453,10 +448,9 @@ private XElement ReplacePackageAttributes(XElement existingNode, PackageReferenc foreach (XName name in existingAttributeNames) { // Clear newValue - string newValue = null; // Try to get newValue correlated to the attribute on the existing node. - PackagesConfig.TryGetAttribute(newEntryNode, name.LocalName, out newValue); + PackagesConfig.TryGetAttribute(newEntryNode, name.LocalName, out var newValue); // When the attribute is not specified a value in the new node if (string.IsNullOrEmpty(newValue)) diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveIOUtility.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveIOUtility.cs index cb34694d86b..d619e2ee34d 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveIOUtility.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveIOUtility.cs @@ -347,9 +347,8 @@ private static UnsignedPackageArchiveMetadata ReadUnsignedArchiveMetadata(Binary reader.BaseStream.Seek(endOfCentralDirectoryRecord.OffsetOfStartOfCentralDirectory, SeekOrigin.Begin); var centralDirectoryRecords = new List(); - CentralDirectoryHeader header; - while (CentralDirectoryHeader.TryRead(reader, out header)) + while (CentralDirectoryHeader.TryRead(reader, out var header)) { var centralDirectoryMetadata = new CentralDirectoryHeaderMetadata() { diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveUtility.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveUtility.cs index 0d133441d9b..b325e63b256 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveUtility.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Archive/SignedPackageArchiveUtility.cs @@ -40,9 +40,8 @@ public static bool IsSigned(BinaryReader reader) // Look for signature central directory record reader.BaseStream.Seek(endOfCentralDirectoryRecord.OffsetOfStartOfCentralDirectory, SeekOrigin.Begin); - CentralDirectoryHeader centralDirectoryHeader; - while (CentralDirectoryHeader.TryRead(reader, out centralDirectoryHeader)) + while (CentralDirectoryHeader.TryRead(reader, out var centralDirectoryHeader)) { if (IsPackageSignatureFileEntry( centralDirectoryHeader.FileName, @@ -52,8 +51,7 @@ public static bool IsSigned(BinaryReader reader) reader.BaseStream.Seek(centralDirectoryHeader.RelativeOffsetOfLocalHeader, SeekOrigin.Begin); // Make sure local file header exists - LocalFileHeader localFileHeader; - if (!LocalFileHeader.TryRead(reader, out localFileHeader)) + if (!LocalFileHeader.TryRead(reader, out var localFileHeader)) { throw new InvalidDataException(Strings.ErrorInvalidPackageArchive); } @@ -117,9 +115,7 @@ private static LocalFileHeader ReadPackageSignatureFileLocalFileHeader( { reader.BaseStream.Seek(signatureCentralDirectoryHeader.OffsetToLocalFileHeader, SeekOrigin.Begin); - LocalFileHeader header; - - if (!LocalFileHeader.TryRead(reader, out header)) + if (!LocalFileHeader.TryRead(reader, out var header)) { throw new SignatureException(NuGetLogCode.NU3005, Strings.InvalidPackageSignatureFile); } @@ -172,9 +168,7 @@ public static bool IsZip64(BinaryReader reader) reader.BaseStream.Seek(endOfCentralDirectoryRecord.OffsetOfStartOfCentralDirectory, SeekOrigin.Begin); - CentralDirectoryHeader centralDirectoryHeader; - - while (CentralDirectoryHeader.TryRead(reader, out centralDirectoryHeader)) + while (CentralDirectoryHeader.TryRead(reader, out var centralDirectoryHeader)) { if (HasZip64ExtendedInformationExtraField(centralDirectoryHeader)) { @@ -190,9 +184,7 @@ public static bool IsZip64(BinaryReader reader) reader.BaseStream.Position = centralDirectoryHeader.RelativeOffsetOfLocalHeader; - LocalFileHeader localFileHeader; - - if (LocalFileHeader.TryRead(reader, out localFileHeader) && + if (LocalFileHeader.TryRead(reader, out var localFileHeader) && HasZip64ExtendedInformationExtraField(localFileHeader)) { return true; @@ -206,9 +198,7 @@ public static bool IsZip64(BinaryReader reader) private static bool HasZip64ExtendedInformationExtraField(CentralDirectoryHeader header) { - IReadOnlyList extraFields; - - if (ExtraField.TryRead(header, out extraFields)) + if (ExtraField.TryRead(header, out var extraFields)) { return extraFields.Any(extraField => extraField is Zip64ExtendedInformationExtraField); } @@ -218,9 +208,7 @@ private static bool HasZip64ExtendedInformationExtraField(CentralDirectoryHeader private static bool HasZip64ExtendedInformationExtraField(LocalFileHeader header) { - IReadOnlyList extraFields; - - if (ExtraField.TryRead(header, out extraFields)) + if (ExtraField.TryRead(header, out var extraFields)) { return extraFields.Any(extraField => extraField is Zip64ExtendedInformationExtraField); } diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Content/SignatureContent.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Content/SignatureContent.cs index 58affe7b5e3..2cb701b1fb2 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Content/SignatureContent.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Content/SignatureContent.cs @@ -168,8 +168,7 @@ private static void ThrowIfSignatureFormatVersionIsUnsupported(Dictionary encodedData, ref BigInteger rid) do { - BigInteger remainder; - unencoded = BigInteger.DivRem(unencoded, divisor, out remainder); + unencoded = BigInteger.DivRem(unencoded, divisor, out var remainder); byte octet = (byte)remainder; octet |= continuance; diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerGeneralizedTime.cs b/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerGeneralizedTime.cs index a6eaf5c45e4..2c1c598f6dc 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerGeneralizedTime.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerGeneralizedTime.cs @@ -77,14 +77,12 @@ public static DerGeneralizedTime Read(string decodedTime) format = $"yyyyMMddHHmmss.{new string('F', fractionalSecondDigits)}Z"; } - DateTime datetime; - if (DateTime.TryParseExact( - stringToParse, - format, - CultureInfo.InvariantCulture, - DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, - out datetime)) + stringToParse, + format, + CultureInfo.InvariantCulture, + DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, + out var datetime)) { return new DerGeneralizedTime(datetime); } diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerSequenceReader.cs b/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerSequenceReader.cs index 61f6eb5cdc7..eb98d688c8a 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerSequenceReader.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/DerEncoding/DerSequenceReader.cs @@ -186,8 +186,7 @@ internal byte[] ReadNextEncodedValue() // Check that the tag is legal, but the value isn't relevant. PeekTag(); - int lengthLength; - int contentLength = ScanContentLength(_data, _position + 1, _end, out lengthLength); + int contentLength = ScanContentLength(_data, _position + 1, _end, out var lengthLength); // Length of tag, encoded length, and the content int totalLength = 1 + lengthLength + contentLength; Debug.Assert(_end - totalLength >= _position); @@ -349,8 +348,7 @@ private DerSequenceReader ReadCollectionWithTag(DerTag expected) // DerSequenceReader wants to read its own tag, so don't EatTag here. CheckTag(expected, _data, _position); - int lengthLength; - int contentLength = ScanContentLength(_data, _position + 1, _end, out lengthLength); + int contentLength = ScanContentLength(_data, _position + 1, _end, out var lengthLength); int totalLength = 1 + lengthLength + contentLength; DerSequenceReader reader = new DerSequenceReader(expected, _data, _position, totalLength); @@ -486,8 +484,6 @@ private DateTime ReadTime(DerTag timeTag, string formatString) decodedTime[decodedTime.Length - 1] == 'Z', $"The date doesn't follow the X.690 format, ending with {decodedTime[decodedTime.Length - 1]}"); - DateTime time; - DateTimeFormatInfo fi = LazyInitializer.EnsureInitialized( ref s_validityDateTimeFormatInfo, () => @@ -503,7 +499,7 @@ private DateTime ReadTime(DerTag timeTag, string formatString) formatString, fi, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, - out time)) + out var time)) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } @@ -570,8 +566,7 @@ private static void CheckTag(DerTag expected, byte[] data, int position) private int EatLength() { - int bytesConsumed; - int answer = ScanContentLength(_data, _position, _end, out bytesConsumed); + int answer = ScanContentLength(_data, _position, _end, out var bytesConsumed); _position += bytesConsumed; return answer; diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/NuGetV3ServiceIndexUrl.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/NuGetV3ServiceIndexUrl.cs index f32f3b50b98..4d9b04e90fe 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/NuGetV3ServiceIndexUrl.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/NuGetV3ServiceIndexUrl.cs @@ -51,9 +51,7 @@ internal static NuGetV3ServiceIndexUrl Read(DerSequenceReader reader) throw new SignatureException(Strings.NuGetV3ServiceIndexUrlInvalid); } - Uri url; - - if (!Uri.TryCreate(urlString, UriKind.Absolute, out url)) + if (!Uri.TryCreate(urlString, UriKind.Absolute, out var url)) { throw new SignatureException(Strings.NuGetV3ServiceIndexUrlInvalid); } diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/Signature.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/Signature.cs index 2b90bcc18e3..ded908e6a07 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/Signature.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Signatures/Signature.cs @@ -223,8 +223,7 @@ public virtual SignatureVerificationSummary Verify( var statusFlags = CertificateChainUtility.DefaultObservedStatusFlags; - IEnumerable messages; - if (CertificateChainUtility.TryGetStatusAndMessage(chainStatuses, statusFlags, out messages)) + if (CertificateChainUtility.TryGetStatusAndMessage(chainStatuses, statusFlags, out var messages)) { foreach (var message in messages) { diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequest.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequest.cs index aa224dfe0ad..39a0cd81412 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequest.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Rfc3161TimestampRequest.cs @@ -58,10 +58,7 @@ public Rfc3161TimestampRequest( if (messageHash == null) throw new ArgumentNullException(nameof(messageHash)); - int expectedSize; - string algorithmIdentifier; - - if (!ResolveAlgorithm(hashAlgorithm, out expectedSize, out algorithmIdentifier)) + if (!ResolveAlgorithm(hashAlgorithm, out var expectedSize, out var algorithmIdentifier)) { throw new ArgumentOutOfRangeException( nameof(hashAlgorithm), diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Timestamp.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Timestamp.cs index 9a91c4c307e..3eb155ed2ae 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Timestamp.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Timestamp/Timestamp.cs @@ -179,11 +179,10 @@ internal SignatureVerificationStatusFlags Verify( else { var chainBuildingHasIssues = false; - IEnumerable messages; var timestampInvalidCertificateFlags = CertificateChainUtility.DefaultObservedStatusFlags; - if (CertificateChainUtility.TryGetStatusAndMessage(chainStatusList, timestampInvalidCertificateFlags, out messages)) + if (CertificateChainUtility.TryGetStatusAndMessage(chainStatusList, timestampInvalidCertificateFlags, out var messages)) { foreach (var message in messages) { diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Utility/CertificateChainUtility.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Utility/CertificateChainUtility.cs index efbac7861de..16dfc87886d 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Utility/CertificateChainUtility.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Utility/CertificateChainUtility.cs @@ -71,10 +71,7 @@ public static IX509CertificateChain GetCertificateChain( return GetCertificateChain(chain.PrivateReference); } - X509ChainStatusFlags errorStatusFlags; - X509ChainStatusFlags warningStatusFlags; - - GetChainStatusFlags(certificate, certificateType, out errorStatusFlags, out warningStatusFlags); + GetChainStatusFlags(certificate, certificateType, out var errorStatusFlags, out var warningStatusFlags); var fatalStatuses = new List(); var logCode = certificateType == CertificateType.Timestamp ? NuGetLogCode.NU3028 : NuGetLogCode.NU3018; diff --git a/src/NuGet.Core/NuGet.Packaging/Signing/Verification/SignatureTrustAndValidityVerificationProvider.cs b/src/NuGet.Core/NuGet.Packaging/Signing/Verification/SignatureTrustAndValidityVerificationProvider.cs index 6648b184903..ee646810507 100644 --- a/src/NuGet.Core/NuGet.Packaging/Signing/Verification/SignatureTrustAndValidityVerificationProvider.cs +++ b/src/NuGet.Core/NuGet.Packaging/Signing/Verification/SignatureTrustAndValidityVerificationProvider.cs @@ -208,9 +208,8 @@ private SignatureVerificationSummary GetTimestamp( { var issues = new List(); SignatureVerificationStatus status; - SignatureVerificationStatusFlags statusFlags; - var succeeded = signature.TryGetValidTimestamp(verifierSettings, _fingerprintAlgorithm, issues, out statusFlags, out timestamp); + var succeeded = signature.TryGetValidTimestamp(verifierSettings, _fingerprintAlgorithm, issues, out var statusFlags, out timestamp); status = VerificationUtility.GetSignatureVerificationStatus(statusFlags); @@ -232,8 +231,7 @@ private SignatureVerificationSummary VerifyValidityAndTrust( SignatureVerifySettings settings, X509Certificate2Collection certificateExtraStore) { - Timestamp timestamp; - var timestampSummary = GetTimestamp(signature, verifierSettings, out timestamp); + var timestampSummary = GetTimestamp(signature, verifierSettings, out var timestamp); var status = signature.Verify( timestamp, diff --git a/src/NuGet.Core/NuGet.ProjectModel/DependencyGraphSpec.cs b/src/NuGet.Core/NuGet.ProjectModel/DependencyGraphSpec.cs index 76322568795..a25afd6601d 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/DependencyGraphSpec.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/DependencyGraphSpec.cs @@ -66,8 +66,7 @@ public PackageSpec GetProjectSpec(string projectUniqueName) throw new ArgumentNullException(nameof(projectUniqueName)); } - PackageSpec project; - _projects.TryGetValue(projectUniqueName, out project); + _projects.TryGetValue(projectUniqueName, out var project); return project; } diff --git a/src/NuGet.Core/NuGet.ProjectModel/JsonUtility.cs b/src/NuGet.Core/NuGet.ProjectModel/JsonUtility.cs index 72a38e87f82..f49bf407893 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/JsonUtility.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/JsonUtility.cs @@ -111,8 +111,7 @@ internal static TItem ReadProperty(JObject jObject, string propertyName) { if (jObject != null) { - JToken value; - if (jObject.TryGetValue(propertyName, out value) && value != null) + if (jObject.TryGetValue(propertyName, out var value) && value != null) { return value.Value(); } diff --git a/src/NuGet.Core/NuGet.ProjectModel/LockFile/BuildAction.cs b/src/NuGet.Core/NuGet.ProjectModel/LockFile/BuildAction.cs index c5c76395b5c..0bd717d60b9 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/LockFile/BuildAction.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/LockFile/BuildAction.cs @@ -37,8 +37,7 @@ private BuildAction(string value, bool isKnown) public static BuildAction Parse(string value) { - BuildAction action; - if (_knownBuildActions.TryGetValue(value, out action)) + if (_knownBuildActions.TryGetValue(value, out var action)) { return action; } diff --git a/src/NuGet.Core/NuGet.ProjectModel/LockFile/LockFileItem.cs b/src/NuGet.Core/NuGet.ProjectModel/LockFile/LockFileItem.cs index e95a1d53ddb..8417f5ac8cc 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/LockFile/LockFileItem.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/LockFile/LockFileItem.cs @@ -77,8 +77,7 @@ public override int GetHashCode() protected string GetProperty(string name) { - string value; - Properties.TryGetValue(name, out value); + Properties.TryGetValue(name, out var value); return value; } diff --git a/src/NuGet.Core/NuGet.ProjectModel/PackageSpecReferenceDependencyProvider.cs b/src/NuGet.Core/NuGet.ProjectModel/PackageSpecReferenceDependencyProvider.cs index aa5e70df663..1492016a013 100644 --- a/src/NuGet.Core/NuGet.ProjectModel/PackageSpecReferenceDependencyProvider.cs +++ b/src/NuGet.Core/NuGet.ProjectModel/PackageSpecReferenceDependencyProvider.cs @@ -251,8 +251,7 @@ private List GetDependenciesFromSpecRestoreMetadata(PackageSp var dependencyName = reference.ProjectPath; var range = VersionRange.All; - ExternalProjectReference externalProject; - if (_externalProjectsByUniqueName.TryGetValue(reference.ProjectUniqueName, out externalProject)) + if (_externalProjectsByUniqueName.TryGetValue(reference.ProjectUniqueName, out var externalProject)) { dependencyName = externalProject.ProjectName; @@ -413,8 +412,7 @@ private List GetChildReferences(ExternalProjectReferen foreach (var reference in parent.ExternalProjectReferences) { - ExternalProjectReference childReference; - if (!_externalProjectsByUniqueName.TryGetValue(reference, out childReference)) + if (!_externalProjectsByUniqueName.TryGetValue(reference, out var childReference)) { // Create a reference to mark that this project is unresolved here childReference = new ExternalProjectReference( diff --git a/src/NuGet.Core/NuGet.Protocol/Converters/SafeBoolConverter.cs b/src/NuGet.Core/NuGet.Protocol/Converters/SafeBoolConverter.cs index 08ce126b9e0..eadd0265b30 100644 --- a/src/NuGet.Core/NuGet.Protocol/Converters/SafeBoolConverter.cs +++ b/src/NuGet.Core/NuGet.Protocol/Converters/SafeBoolConverter.cs @@ -21,8 +21,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist case JsonToken.Boolean: return serializer.Deserialize(reader); case JsonToken.String: - bool flag; - if (Boolean.TryParse(reader.Value.ToString().Trim(), out flag)) + if (Boolean.TryParse(reader.Value.ToString().Trim(), out var flag)) { return flag; } diff --git a/src/NuGet.Core/NuGet.Protocol/Converters/SafeUriConverter.cs b/src/NuGet.Core/NuGet.Protocol/Converters/SafeUriConverter.cs index 83f3ce51d81..3ed9ee002be 100644 --- a/src/NuGet.Core/NuGet.Protocol/Converters/SafeUriConverter.cs +++ b/src/NuGet.Core/NuGet.Protocol/Converters/SafeUriConverter.cs @@ -19,8 +19,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist case JsonToken.Null: return null; case JsonToken.String: - Uri uri; - if (Uri.TryCreate(reader.Value.ToString().Trim(), UriKind.Absolute, out uri)) + if (Uri.TryCreate(reader.Value.ToString().Trim(), UriKind.Absolute, out var uri)) { return uri; } diff --git a/src/NuGet.Core/NuGet.Protocol/DependencyInfo/ResolverMetadataClient.cs b/src/NuGet.Core/NuGet.Protocol/DependencyInfo/ResolverMetadataClient.cs index 64b34332fa9..3ba9af26652 100644 --- a/src/NuGet.Core/NuGet.Protocol/DependencyInfo/ResolverMetadataClient.cs +++ b/src/NuGet.Core/NuGet.Protocol/DependencyInfo/ResolverMetadataClient.cs @@ -84,10 +84,8 @@ private static RemoteSourceDependencyInfo ProcessPackageVersion(JObject packageO var groupDependencies = new List(); - JToken dependenciesObj; - // Packages with no dependencies have 'dependencyGroups' but no 'dependencies' - if (dependencyGroupObj.TryGetValue("dependencies", out dependenciesObj)) + if (dependencyGroupObj.TryGetValue("dependencies", out var dependenciesObj)) { foreach (JObject dependencyObj in dependenciesObj) { diff --git a/src/NuGet.Core/NuGet.Protocol/HttpSource/HttpRequestMessageExtensions.cs b/src/NuGet.Core/NuGet.Protocol/HttpSource/HttpRequestMessageExtensions.cs index 954171dc34e..c2efe0a23df 100644 --- a/src/NuGet.Core/NuGet.Protocol/HttpSource/HttpRequestMessageExtensions.cs +++ b/src/NuGet.Core/NuGet.Protocol/HttpSource/HttpRequestMessageExtensions.cs @@ -134,8 +134,7 @@ private static T GetProperty(this HttpRequestMessage request, string key) #if NET5_0_OR_GREATER if (request.Options.TryGetValue(new HttpRequestOptionsKey(key), out T result)) #else - object result; - if (request.Properties.TryGetValue(key, out result) && result is T) + if (request.Properties.TryGetValue(key, out var result) && result is T) #endif { return (T)result; diff --git a/src/NuGet.Core/NuGet.Protocol/HttpSource/StsAuthenticationHandler.cs b/src/NuGet.Core/NuGet.Protocol/HttpSource/StsAuthenticationHandler.cs index f264afa7c73..b210679675c 100644 --- a/src/NuGet.Core/NuGet.Protocol/HttpSource/StsAuthenticationHandler.cs +++ b/src/NuGet.Core/NuGet.Protocol/HttpSource/StsAuthenticationHandler.cs @@ -191,8 +191,7 @@ private static string AcquireSTSToken(string endpoint, string realm) private static string GetHeader(HttpResponseMessage response, string header) { - IEnumerable values; - if (response.Headers.TryGetValues(header, out values)) + if (response.Headers.TryGetValues(header, out var values)) { return values.FirstOrDefault(); } diff --git a/src/NuGet.Core/NuGet.Protocol/HttpSource/TokenStore.cs b/src/NuGet.Core/NuGet.Protocol/HttpSource/TokenStore.cs index c41dba300f8..07a015acf1d 100644 --- a/src/NuGet.Core/NuGet.Protocol/HttpSource/TokenStore.cs +++ b/src/NuGet.Core/NuGet.Protocol/HttpSource/TokenStore.cs @@ -16,8 +16,7 @@ public class TokenStore public string GetToken(Uri sourceUri) { - string token; - if (_tokenCache.TryGetValue(sourceUri, out token)) + if (_tokenCache.TryGetValue(sourceUri, out var token)) { return token; } 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/LegacyFeed/V2FeedPackageInfo.cs b/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedPackageInfo.cs index 43606cc691c..bff94cdb630 100644 --- a/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedPackageInfo.cs +++ b/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedPackageInfo.cs @@ -183,8 +183,7 @@ public int DownloadCountAsInt { get { - int x = 0; - _ = int.TryParse(_downloadCount, out x); + _ = int.TryParse(_downloadCount, out var x); return x; } } @@ -287,8 +286,7 @@ public IReadOnlyList DependencySets } // Group dependencies by target framework - List deps = null; - if (!results.TryGetValue(framework, out deps)) + if (!results.TryGetValue(framework, out var deps)) { deps = new List(); results.Add(framework, deps); diff --git a/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedParser.cs b/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedParser.cs index fb06ef1adc2..d8c08f6282a 100644 --- a/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedParser.cs +++ b/src/NuGet.Core/NuGet.Protocol/LegacyFeed/V2FeedParser.cs @@ -414,8 +414,7 @@ private static string GetString(XElement parent, XName childName) { var dateString = GetString(parent, childName); - DateTimeOffset date; - if (DateTimeOffset.TryParse(dateString, out date)) + if (DateTimeOffset.TryParse(dateString, out var date)) { return date; } diff --git a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/FindLocalPackagesResourceUnzipped.cs b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/FindLocalPackagesResourceUnzipped.cs index 1c0f8381f33..abf4837dae9 100644 --- a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/FindLocalPackagesResourceUnzipped.cs +++ b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/FindLocalPackagesResourceUnzipped.cs @@ -37,15 +37,13 @@ public override IEnumerable FindPackagesById(string id, ILogge public override LocalPackageInfo GetPackage(Uri path, ILogger logger, CancellationToken token) { - LocalPackageInfo package; - _pathIndex.Value.TryGetValue(path, out package); + _pathIndex.Value.TryGetValue(path, out var package); return package; } public override LocalPackageInfo GetPackage(PackageIdentity identity, ILogger logger, CancellationToken token) { - LocalPackageInfo package; - _index.Value.TryGetValue(identity, out package); + _index.Value.TryGetValue(identity, out var package); return package; } diff --git a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs index 55c067e14d7..87457a5801a 100644 --- a/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/LocalRepositories/LocalV3FindPackageByIdResource.cs @@ -500,8 +500,7 @@ private List GetVersionsCore(string id, ILogger logger) var versionPart = versionDir.Name; // Get the version part and parse it - NuGetVersion version; - if (!NuGetVersion.TryParse(versionPart, out version)) + if (!NuGetVersion.TryParse(versionPart, out var version)) { logger.LogWarning(string.Format( CultureInfo.CurrentCulture, diff --git a/src/NuGet.Core/NuGet.Protocol/Model/PackageSearchMetadataV2Feed.cs b/src/NuGet.Core/NuGet.Protocol/Model/PackageSearchMetadataV2Feed.cs index 33118603e89..1cbaec550b7 100644 --- a/src/NuGet.Core/NuGet.Protocol/Model/PackageSearchMetadataV2Feed.cs +++ b/src/NuGet.Core/NuGet.Protocol/Model/PackageSearchMetadataV2Feed.cs @@ -35,8 +35,7 @@ public PackageSearchMetadataV2Feed(V2FeedPackageInfo package) Version = package.Version; IsListed = package.IsListed; - long count; - if (long.TryParse(package.DownloadCount, out count)) + if (long.TryParse(package.DownloadCount, out var count)) { DownloadCount = count; } @@ -64,8 +63,7 @@ public PackageSearchMetadataV2Feed(V2FeedPackageInfo package, MetadataReferenceC Version = package.Version; IsListed = package.IsListed; - long count; - if (long.TryParse(package.DownloadCount, out count)) + if (long.TryParse(package.DownloadCount, out var count)) { DownloadCount = count; } @@ -141,8 +139,7 @@ public string Title private static Uri GetUriSafe(string url) { - Uri uri = null; - Uri.TryCreate(url, UriKind.Absolute, out uri); + Uri.TryCreate(url, UriKind.Absolute, out var uri); return uri; } diff --git a/src/NuGet.Core/NuGet.Protocol/Model/VersionInfo.cs b/src/NuGet.Core/NuGet.Protocol/Model/VersionInfo.cs index 302cb8be698..7150d60c7a8 100644 --- a/src/NuGet.Core/NuGet.Protocol/Model/VersionInfo.cs +++ b/src/NuGet.Core/NuGet.Protocol/Model/VersionInfo.cs @@ -16,8 +16,7 @@ public VersionInfo(NuGetVersion version, string downloadCount) { Version = version; - long count; - if (long.TryParse(downloadCount, out count)) + if (long.TryParse(downloadCount, out var count)) { DownloadCount = count; } diff --git a/src/NuGet.Core/NuGet.Protocol/NuGetTestMode.cs b/src/NuGet.Core/NuGet.Protocol/NuGetTestMode.cs index 9f650d40096..97145e06fc8 100644 --- a/src/NuGet.Core/NuGet.Protocol/NuGetTestMode.cs +++ b/src/NuGet.Core/NuGet.Protocol/NuGetTestMode.cs @@ -28,8 +28,7 @@ private static bool FromEnvironmentVariable() return false; } - bool isEnabled; - return Boolean.TryParse(testMode, out isEnabled) && isEnabled; + return Boolean.TryParse(testMode, out var isEnabled) && isEnabled; } diff --git a/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepository.cs b/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepository.cs index 09bad9b6985..a4fb7c62c55 100644 --- a/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepository.cs +++ b/src/NuGet.Core/NuGet.Protocol/PackagesFolder/NuGetv3LocalRepository.cs @@ -153,14 +153,12 @@ private List GetPackages(string id) foreach (var fullVersionDir in Directory.EnumerateDirectories(packageIdRoot)) { - LocalPackageInfo package; - if (!_packageCache.TryGetValue(fullVersionDir, out package)) + if (!_packageCache.TryGetValue(fullVersionDir, out var package)) { var versionPart = fullVersionDir.Substring(packageIdRoot.Length).TrimStart(Path.DirectorySeparatorChar); // Get the version part and parse it - NuGetVersion version; - if (!NuGetVersion.TryParse(versionPart, out version)) + if (!NuGetVersion.TryParse(versionPart, out var version)) { continue; } diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs index 89cbb518b8f..1f202522367 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/MessageDispatcher.cs @@ -532,9 +532,7 @@ private void OnMessageReceived(object sender, MessageEventArgs e) return; } - OutboundRequestContext requestContext; - - if (_outboundRequestContexts.TryGetValue(e.Message.RequestId, out requestContext)) + if (_outboundRequestContexts.TryGetValue(e.Message.RequestId, out var requestContext)) { switch (e.Message.Type) { @@ -590,9 +588,7 @@ private void OnMessageReceived(object sender, MessageEventArgs e) private void HandleInboundCancel(Message message) { - InboundRequestContext requestContext; - - if (_inboundRequestContexts.TryGetValue(message.RequestId, out requestContext)) + if (_inboundRequestContexts.TryGetValue(message.RequestId, out var requestContext)) { requestContext.Cancel(); } @@ -642,9 +638,7 @@ private void HandleInboundRequest(Message message) private IRequestHandler GetInboundRequestHandler(MessageMethod method) { - IRequestHandler handler; - - if (!RequestHandlers.TryGet(method, out handler)) + if (!RequestHandlers.TryGet(method, out var handler)) { throw new ProtocolException( string.Format(CultureInfo.CurrentCulture, Strings.Plugin_RequestHandlerDoesNotExist, method)); @@ -655,9 +649,7 @@ private IRequestHandler GetInboundRequestHandler(MessageMethod method) private OutboundRequestContext GetOutboundRequestContext(string requestId) { - OutboundRequestContext requestContext; - - if (!_outboundRequestContexts.TryGetValue(requestId, out requestContext)) + if (!_outboundRequestContexts.TryGetValue(requestId, out var requestContext)) { throw new ProtocolException( string.Format(CultureInfo.CurrentCulture, Strings.Plugin_RequestContextDoesNotExist, requestId)); @@ -668,9 +660,7 @@ private OutboundRequestContext GetOutboundRequestContext(string requestId) private void RemoveInboundRequestContext(string requestId) { - InboundRequestContext requestContext; - - if (_inboundRequestContexts.TryRemove(requestId, out requestContext)) + if (_inboundRequestContexts.TryRemove(requestId, out var requestContext)) { requestContext.Dispose(); } @@ -678,9 +668,7 @@ private void RemoveInboundRequestContext(string requestId) private void RemoveOutboundRequestContext(string requestId) { - OutboundRequestContext requestContext; - - if (_outboundRequestContexts.TryRemove(requestId, out requestContext)) + if (_outboundRequestContexts.TryRemove(requestId, out var requestContext)) { requestContext.Dispose(); } diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs index c522406552f..8bf27bbfb0b 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginFactory.cs @@ -379,9 +379,7 @@ private void Dispose(IPlugin plugin) UnregisterEventHandlers(plugin as Plugin); - Lazy> lazyTask; - - if (_plugins.TryRemove(plugin.FilePath, out lazyTask)) + if (_plugins.TryRemove(plugin.FilePath, out var lazyTask)) { if (lazyTask.IsValueCreated && lazyTask.Value.Status == TaskStatus.RanToCompletion) { diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs index e659a58e416..3f2df9b2c65 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/PluginPackageReader.cs @@ -1000,8 +1000,7 @@ private async Task> GetFileGroupsAsync( // Use the known framework or if the folder did not parse, use the Any framework and consider it a sub folder var framework = GetFrameworkFromPath(path, allowSubFolders); - List items = null; - if (!groups.TryGetValue(framework, out items)) + if (!groups.TryGetValue(framework, out var items)) { items = new List(); groups.Add(framework, items); diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs index ac5322fc384..307dd54a835 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetCredentialsRequestHandler.cs @@ -291,9 +291,7 @@ private static CredentialRequestType GetCredentialRequestType(HttpStatusCode sta private PackageSource GetPackageSource(string packageSourceRepository) { - SourceRepository sourceRepository; - - if (_repositories.TryGetValue(packageSourceRepository, out sourceRepository)) + if (_repositories.TryGetValue(packageSourceRepository, out var sourceRepository)) { return sourceRepository.PackageSource; } diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs index 3fae582822b..4d6d00c5946 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/RequestHandlers/GetServiceIndexRequestHandler.cs @@ -116,11 +116,10 @@ public async Task HandleResponseAsync( cancellationToken.ThrowIfCancellationRequested(); var getRequest = MessageUtilities.DeserializePayload(request); - SourceRepository sourceRepository; ServiceIndexResourceV3 serviceIndex = null; GetServiceIndexResponse responsePayload; - if (_repositories.TryGetValue(getRequest.PackageSourceRepository, out sourceRepository)) + if (_repositories.TryGetValue(getRequest.PackageSourceRepository, out var sourceRepository)) { serviceIndex = await sourceRepository.GetResourceAsync(cancellationToken); } diff --git a/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs b/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs index a792e7b7ab7..39655b2e876 100644 --- a/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs +++ b/src/NuGet.Core/NuGet.Protocol/Plugins/TimeoutUtilities.cs @@ -28,8 +28,7 @@ public static TimeSpan GetTimeout(string timeoutInSeconds, TimeSpan fallbackTime Strings.Plugin_TimeoutOutOfRange); } - int seconds; - if (int.TryParse(timeoutInSeconds, out seconds)) + if (int.TryParse(timeoutInSeconds, out var seconds)) { try { diff --git a/src/NuGet.Core/NuGet.Protocol/Providers/ServiceIndexResourceV3Provider.cs b/src/NuGet.Core/NuGet.Protocol/Providers/ServiceIndexResourceV3Provider.cs index 5d079558a45..7ba5e3dd6be 100644 --- a/src/NuGet.Core/NuGet.Protocol/Providers/ServiceIndexResourceV3Provider.cs +++ b/src/NuGet.Core/NuGet.Protocol/Providers/ServiceIndexResourceV3Provider.cs @@ -194,12 +194,10 @@ private static async Task ConsumeServiceIndexStreamAsync // Use SemVer instead of NuGetVersion, the service index should always be // in strict SemVer format - JToken versionToken; - if (json.TryGetValue("version", out versionToken) && + if (json.TryGetValue("version", out var versionToken) && versionToken.Type == JTokenType.String) { - SemanticVersion version; - if (SemanticVersion.TryParse((string)versionToken, out version) && + if (SemanticVersion.TryParse((string)versionToken, out var version) && version.Major == 3) { return new ServiceIndexResourceV3(json, utcNow, source); diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs index 53adcdf5a61..794c3c185ed 100644 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/HttpFileSystemBasedFindPackageByIdResource.cs @@ -194,8 +194,7 @@ public override async Task GetDependencyInfoAsync var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - PackageInfo packageInfo; - if (packageInfos.TryGetValue(version, out packageInfo)) + if (packageInfos.TryGetValue(version, out var packageInfo)) { var reader = await _nupkgDownloader.GetNuspecReaderFromNupkgAsync( packageInfo.Identity, @@ -280,8 +279,7 @@ public override async Task CopyNupkgToStreamAsync( var packageInfos = await EnsurePackagesAsync(id, cacheContext, logger, cancellationToken); - PackageInfo packageInfo; - if (packageInfos.TryGetValue(version, out packageInfo)) + if (packageInfos.TryGetValue(version, out var packageInfo)) { return await _nupkgDownloader.CopyNupkgToStreamAsync( packageInfo.Identity, @@ -344,8 +342,7 @@ public override async Task GetPackageDownloaderAsync( var packageInfos = await EnsurePackagesAsync(packageIdentity.Id, cacheContext, logger, cancellationToken); - PackageInfo packageInfo; - if (packageInfos.TryGetValue(packageIdentity.Version, out packageInfo)) + if (packageInfos.TryGetValue(packageIdentity.Version, out var packageInfo)) { return new RemotePackageArchiveDownloader(_httpSource.PackageSource, this, packageInfo.Identity, cacheContext, logger); } diff --git a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs index 8ab91f64bad..45985d08927 100644 --- a/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/RemoteRepositories/PluginFindPackageByIdResource.cs @@ -267,9 +267,7 @@ public override async Task GetDependencyInfoAsync var packageInfos = await EnsurePackagesAsync(id, cacheContext, cancellationToken); - PackageInfo packageInfo; - - if (packageInfos.TryGetValue(version, out packageInfo)) + if (packageInfos.TryGetValue(version, out var packageInfo)) { AddOrUpdateLogger(_plugin, logger); 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.Protocol/Resources/PackageDetailsUriResourceV3.cs b/src/NuGet.Core/NuGet.Protocol/Resources/PackageDetailsUriResourceV3.cs index 25a3b940d70..ad950a31de5 100644 --- a/src/NuGet.Core/NuGet.Protocol/Resources/PackageDetailsUriResourceV3.cs +++ b/src/NuGet.Core/NuGet.Protocol/Resources/PackageDetailsUriResourceV3.cs @@ -29,8 +29,7 @@ public static PackageDetailsUriResourceV3 CreateOrNull(string uriTemplate) private static bool IsValidUriTemplate(string uriTemplate) { - Uri uri; - var isValidUri = Uri.TryCreate(uriTemplate, UriKind.Absolute, out uri); + var isValidUri = Uri.TryCreate(uriTemplate, UriKind.Absolute, out var uri); // Only allow HTTPS package details URLs. if (isValidUri && !uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs b/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs index a6c185a4cab..4f565c0232b 100644 --- a/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs +++ b/src/NuGet.Core/NuGet.Protocol/Resources/PluginResource.cs @@ -108,9 +108,8 @@ private SetCredentialsRequest CreateRequest() string proxyPassword = null; string username = null; string password = null; - ICredentials credentials; - if (TryGetCachedCredentials(sourceUri, isProxy: true, credentials: out credentials)) + if (TryGetCachedCredentials(sourceUri, isProxy: true, credentials: out var credentials)) { var proxyCredential = credentials.GetCredential(sourceUri, _basicAuthenticationType); diff --git a/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs b/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs index c32b0996aaf..38983be472e 100644 --- a/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs +++ b/src/NuGet.Core/NuGet.Protocol/Resources/ServiceIndexResourceV3.cs @@ -82,8 +82,7 @@ public virtual IReadOnlyList GetServiceEntries(NuGetVersion c foreach (var type in orderedTypes) { - List entries; - if (_index.TryGetValue(type, out entries)) + if (_index.TryGetValue(type, out var entries)) { var compatible = GetBestVersionMatchForType(clientVersion, entries); @@ -150,15 +149,13 @@ private static IDictionary> MakeLookup(JObject i { var result = new Dictionary>(StringComparer.Ordinal); - JToken resources; - if (index.TryGetValue("resources", out resources)) + if (index.TryGetValue("resources", out var resources)) { foreach (var resource in resources) { var id = GetValues(resource["@id"]).SingleOrDefault(); - Uri uri; - if (string.IsNullOrEmpty(id) || !Uri.TryCreate(id, UriKind.Absolute, out uri)) + if (string.IsNullOrEmpty(id) || !Uri.TryCreate(id, UriKind.Absolute, out var uri)) { // Skip invalid or missing @ids continue; @@ -185,8 +182,7 @@ private static IDictionary> MakeLookup(JObject i // Parse supported versions foreach (var versionString in GetValues(clientVersionToken)) { - SemanticVersion version; - if (SemanticVersion.TryParse(versionString, out version)) + if (SemanticVersion.TryParse(versionString, out var version)) { clientVersions.Add(version); } @@ -198,8 +194,7 @@ private static IDictionary> MakeLookup(JObject i { foreach (var version in clientVersions) { - List entries; - if (!result.TryGetValue(type, out entries)) + if (!result.TryGetValue(type, out var entries)) { entries = new List(); result.Add(type, entries); diff --git a/src/NuGet.Core/NuGet.Protocol/SourceRepository.cs b/src/NuGet.Core/NuGet.Protocol/SourceRepository.cs index 91ba3d554fa..7956cb963a4 100644 --- a/src/NuGet.Core/NuGet.Protocol/SourceRepository.cs +++ b/src/NuGet.Core/NuGet.Protocol/SourceRepository.cs @@ -148,9 +148,8 @@ public virtual async Task GetResourceAsync() where T : class, INuGetResour public virtual async Task GetResourceAsync(CancellationToken token) where T : class, INuGetResource { var resourceType = typeof(T); - INuGetResourceProvider[] possible = null; - if (_providerCache.TryGetValue(resourceType, out possible)) + if (_providerCache.TryGetValue(resourceType, out var possible)) { foreach (var provider in possible) { diff --git a/src/NuGet.Core/NuGet.Protocol/Utility/LocalFolderUtility.cs b/src/NuGet.Core/NuGet.Protocol/Utility/LocalFolderUtility.cs index 13d83bfef05..d81eb6c0c94 100644 --- a/src/NuGet.Core/NuGet.Protocol/Utility/LocalFolderUtility.cs +++ b/src/NuGet.Core/NuGet.Protocol/Utility/LocalFolderUtility.cs @@ -598,8 +598,7 @@ private static NuGetVersion GetVersionFromIdVersionString(string idVersionString { var versionString = idVersionString.Substring(prefix.Length); - NuGetVersion version; - if (NuGetVersion.TryParse(versionString, out version)) + if (NuGetVersion.TryParse(versionString, out var version)) { return version; } @@ -1256,8 +1255,7 @@ private static List GetNupkgsFromDirectory(DirectoryInfo root, ILogger private static LocalPackageInfo GetPackageV3(string root, string id, string version, ILogger log) { - NuGetVersion nugetVersion; - if (NuGetVersion.TryParse(version, out nugetVersion)) + if (NuGetVersion.TryParse(version, out var nugetVersion)) { var identity = new PackageIdentity(id, nugetVersion); diff --git a/src/NuGet.Core/NuGet.Protocol/Utility/MetadataReferenceCache.cs b/src/NuGet.Core/NuGet.Protocol/Utility/MetadataReferenceCache.cs index 32d988aeddd..83f3feb769f 100644 --- a/src/NuGet.Core/NuGet.Protocol/Utility/MetadataReferenceCache.cs +++ b/src/NuGet.Core/NuGet.Protocol/Utility/MetadataReferenceCache.cs @@ -36,9 +36,7 @@ public string GetString(string s) return string.Empty; } - string cachedValue; - - if (!_stringCache.TryGetValue(s, out cachedValue)) + if (!_stringCache.TryGetValue(s, out var cachedValue)) { _stringCache.Add(s, s); cachedValue = s; @@ -57,8 +55,7 @@ public NuGetVersion GetVersion(string s) return NuGetVersion.Parse(s); } - NuGetVersion version; - if (!_versionCache.TryGetValue(s, out version)) + if (!_versionCache.TryGetValue(s, out var version)) { version = NuGetVersion.Parse(s); _versionCache.Add(s, version); @@ -91,10 +88,9 @@ public NuGetVersion GetVersion(string s) public T GetObject(T input) { // Get all properties that contain both a Get method and a Set method and can be cached. - PropertyInfo[] properties; Type typeKey = typeof(T); - if (!_propertyCache.TryGetValue(typeKey, out properties)) + if (!_propertyCache.TryGetValue(typeKey, out var properties)) { properties = typeKey.GetTypeInfo() .DeclaredProperties.Where( diff --git a/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs b/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs index 1602b765daa..db3ebd3e425 100644 --- a/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs +++ b/src/NuGet.Core/NuGet.Protocol/Utility/OfflineFeedUtility.cs @@ -154,8 +154,7 @@ public static async Task AddPackageToSource( packageIdentity = packageReader.GetIdentity(); - bool isValidPackage; - if (PackageExists(packageIdentity, source, out isValidPackage)) + if (PackageExists(packageIdentity, source, out var isValidPackage)) { // Package already exists. Verify if it is valid if (isValidPackage) diff --git a/src/NuGet.Core/NuGet.Resolver/PackageResolver.cs b/src/NuGet.Core/NuGet.Resolver/PackageResolver.cs index ddcc7b2aa8f..03d824ff7ac 100644 --- a/src/NuGet.Core/NuGet.Resolver/PackageResolver.cs +++ b/src/NuGet.Core/NuGet.Resolver/PackageResolver.cs @@ -275,8 +275,7 @@ private static List InnerPruneImpossiblePackages(Li { foreach (var dependency in package?.Dependencies) { - IList dependencyVersionRanges; - if (dependencyRangesByPackageId.TryGetValue(dependency.Id, out dependencyVersionRanges)) + if (dependencyRangesByPackageId.TryGetValue(dependency.Id, out var dependencyVersionRanges)) { dependencyVersionRanges.Add(dependency.VersionRange); } diff --git a/src/NuGet.Core/NuGet.Resolver/ResolverComparer.cs b/src/NuGet.Core/NuGet.Resolver/ResolverComparer.cs index 83e07937a22..ec1fdd1ade3 100644 --- a/src/NuGet.Core/NuGet.Resolver/ResolverComparer.cs +++ b/src/NuGet.Core/NuGet.Resolver/ResolverComparer.cs @@ -120,8 +120,7 @@ public int Compare(ResolverPackage x, ResolverPackage y) if (packageBehavior != DependencyBehavior.Highest && packageBehavior != DependencyBehavior.Ignore) { - NuGetVersion installedVersion = null; - if (_installedVersions.TryGetValue(x.Id, out installedVersion)) + if (_installedVersions.TryGetValue(x.Id, out var installedVersion)) { var xvDowngrade = _versionComparer.Compare(xv, installedVersion) < 0; var yvDowngrade = _versionComparer.Compare(yv, installedVersion) < 0; diff --git a/src/NuGet.Core/NuGet.Versioning/VersionComparer.cs b/src/NuGet.Core/NuGet.Versioning/VersionComparer.cs index b023fcab21c..d5c746c119c 100644 --- a/src/NuGet.Core/NuGet.Versioning/VersionComparer.cs +++ b/src/NuGet.Core/NuGet.Versioning/VersionComparer.cs @@ -320,13 +320,11 @@ private static int CompareReleaseLabels(string[] version1, string[] version2) /// private static int CompareRelease(string version1, string version2) { - var version1Num = 0; - var version2Num = 0; var result = 0; // check if the identifiers are numeric - var v1IsNumeric = int.TryParse(version1, out version1Num); - var v2IsNumeric = int.TryParse(version2, out version2Num); + var v1IsNumeric = int.TryParse(version1, out var version1Num); + var v2IsNumeric = int.TryParse(version2, out var version2Num); // if both are numeric compare them as numbers if (v1IsNumeric && v2IsNumeric) 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..e07cd8b04c1 100644 --- a/src/NuGet.Core/NuGet.Versioning/VersionRangeFactory.cs +++ b/src/NuGet.Core/NuGet.Versioning/VersionRangeFactory.cs @@ -74,8 +74,7 @@ public static VersionRange Parse(string value, bool allowFloating) throw new ArgumentNullException(nameof(value)); } - VersionRange? versionInfo; - if (!TryParse(value, allowFloating, out versionInfo)) + if (!TryParse(value, allowFloating, out var versionInfo)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture,