提交 4df36d22 编写于 作者: C Cyrus Najmabadi

Use implicit object creation in VS layer.

上级 04449862
......@@ -30,7 +30,7 @@ private struct CacheValue
private readonly Dictionary<K, CacheValue> _cache;
private readonly LinkedList<K> _nodeList;
// This is a naive course-grained lock, it can probably be optimized
private readonly object _lockObject = new object();
private readonly object _lockObject = new();
public ConcurrentLruCache(int capacity)
{
......
......@@ -27,7 +27,7 @@ internal class VisualStudioExperimentationService : ForegroundThreadAffinitizedO
/// lifetime of the session, so it's fine for us to cache things to avoid the heavy cost of querying for them
/// over and over.
/// </summary>
private readonly Dictionary<string, bool> _experimentEnabledMap = new Dictionary<string, bool>();
private readonly Dictionary<string, bool> _experimentEnabledMap = new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
......
......@@ -10,7 +10,7 @@ namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api
{
internal static class UnitTestingRemoteHostOptionsAccessor
{
public static Option<bool> OOP64Bit => new Option<bool>(
public static Option<bool> OOP64Bit => new(
RemoteHostOptions.OOP64Bit.Feature, RemoteHostOptions.OOP64Bit.Name, defaultValue: RemoteHostOptions.OOP64Bit.DefaultValue,
storageLocations: RemoteHostOptions.OOP64Bit.StorageLocations.ToArray());
}
......
......@@ -37,25 +37,25 @@ internal static class Guids
/// A <see cref="UIContext"/> that is set if there is a C# project in the <see cref="VisualStudioWorkspace"/>.
/// </summary>
public const string CSharpProjectExistsInWorkspaceUIContextString = "CA719A03-D55C-48F9-85DE-D934346E7F70";
public static readonly Guid CSharpProjectExistsInWorkspaceUIContext = new Guid(CSharpProjectExistsInWorkspaceUIContextString);
public static readonly Guid CSharpProjectExistsInWorkspaceUIContext = new(CSharpProjectExistsInWorkspaceUIContextString);
public const string CSharpProjectRootIdString = "C7FEDB89-B36D-4a62-93F4-DC7A95999921";
// from debugger\idl\makeapi\guid.c
public const string CSharpDebuggerLanguageIdString = "3f5162f8-07c6-11d3-9053-00c04fa302a1";
public static readonly Guid CSharpPackageId = new Guid(CSharpPackageIdString);
public static readonly Guid CSharpProjectId = new Guid(CSharpProjectIdString);
public static readonly Guid CSharpLanguageServiceId = new Guid(CSharpLanguageServiceIdString);
public static readonly Guid CSharpEditorFactoryId = new Guid(CSharpEditorFactoryIdString);
public static readonly Guid CSharpCodePageEditorFactoryId = new Guid(CSharpCodePageEditorFactoryIdString);
public static readonly Guid CSharpCommandSetId = new Guid(CSharpCommandSetIdString); // guidCSharpCmdId
public static readonly Guid CSharpGroupId = new Guid(CSharpGroupIdString); // guidCSharpGrpId
public static readonly Guid CSharpRefactorIconId = new Guid(CSharpRefactorIconIdString); // guidCSharpRefactorIcon
public static readonly Guid CSharpGenerateIconId = new Guid(CSharpGenerateIconIdString); // guidCSharpGenerateIcon
public static readonly Guid CSharpOrganizeIconId = new Guid(CSharpOrganizeIconIdString); // guidCSharpOrganizeIcon
public static readonly Guid CSharpDebuggerLanguageId = new Guid(CSharpDebuggerLanguageIdString);
public static readonly Guid CSharpLibraryId = new Guid(CSharpLibraryIdString);
public static readonly Guid CSharpPackageId = new(CSharpPackageIdString);
public static readonly Guid CSharpProjectId = new(CSharpProjectIdString);
public static readonly Guid CSharpLanguageServiceId = new(CSharpLanguageServiceIdString);
public static readonly Guid CSharpEditorFactoryId = new(CSharpEditorFactoryIdString);
public static readonly Guid CSharpCodePageEditorFactoryId = new(CSharpCodePageEditorFactoryIdString);
public static readonly Guid CSharpCommandSetId = new(CSharpCommandSetIdString); // guidCSharpCmdId
public static readonly Guid CSharpGroupId = new(CSharpGroupIdString); // guidCSharpGrpId
public static readonly Guid CSharpRefactorIconId = new(CSharpRefactorIconIdString); // guidCSharpRefactorIcon
public static readonly Guid CSharpGenerateIconId = new(CSharpGenerateIconIdString); // guidCSharpGenerateIcon
public static readonly Guid CSharpOrganizeIconId = new(CSharpOrganizeIconIdString); // guidCSharpOrganizeIcon
public static readonly Guid CSharpDebuggerLanguageId = new(CSharpDebuggerLanguageIdString);
public static readonly Guid CSharpLibraryId = new(CSharpLibraryIdString);
// option page guids from csharp\rad\pkg\guids.h
public const string CSharpOptionPageAdvancedIdString = "8FD0B177-B244-4A97-8E37-6FB7B27DE3AF";
......@@ -88,19 +88,19 @@ internal static class Guids
/// A <see cref="UIContext"/> that is set if there is a Visual Basic project in the <see cref="VisualStudioWorkspace"/>.
/// </summary>
public const string VisualBasicProjectExistsInWorkspaceUIContextString = "EEC3DF0D-6D3F-4544-ABF9-8E26E6A90275";
public static readonly Guid VisualBasicProjectExistsInWorkspaceUIContext = new Guid(VisualBasicProjectExistsInWorkspaceUIContextString);
public static readonly Guid VisualBasicProjectExistsInWorkspaceUIContext = new(VisualBasicProjectExistsInWorkspaceUIContextString);
public static readonly Guid VisualBasicPackageId = new Guid(VisualBasicPackageIdString);
public static readonly Guid VisualBasicCompilerServiceId = new Guid(VisualBasicCompilerServiceIdString);
public static readonly Guid VisualBasicLanguageServiceId = new Guid(VisualBasicLanguageServiceIdString);
public static readonly Guid VisualBasicEditorFactoryId = new Guid(VisualBasicEditorFactoryIdString);
public static readonly Guid VisualBasicCodePageEditorFactoryId = new Guid(VisualBasicCodePageEditorFactoryIdString);
public static readonly Guid VisualBasicLibraryId = new Guid(VisualBasicLibraryIdString);
public static readonly Guid VisualBasicPackageId = new(VisualBasicPackageIdString);
public static readonly Guid VisualBasicCompilerServiceId = new(VisualBasicCompilerServiceIdString);
public static readonly Guid VisualBasicLanguageServiceId = new(VisualBasicLanguageServiceIdString);
public static readonly Guid VisualBasicEditorFactoryId = new(VisualBasicEditorFactoryIdString);
public static readonly Guid VisualBasicCodePageEditorFactoryId = new(VisualBasicCodePageEditorFactoryIdString);
public static readonly Guid VisualBasicLibraryId = new(VisualBasicLibraryIdString);
public static readonly Guid VisualBasicProjectId = new Guid(VisualBasicProjectIdString);
public static readonly Guid VisualBasicProjectId = new(VisualBasicProjectIdString);
// from debugger\idl\makeapi\guid.c
public static readonly Guid VisualBasicDebuggerLanguageId = new Guid(VisualBasicDebuggerLanguageIdString);
public static readonly Guid VisualBasicDebuggerLanguageId = new(VisualBasicDebuggerLanguageIdString);
// option page guid from setupauthoring\vb\components\vblanguageservice.pkgdef
public const string VisualBasicOptionPageVBSpecificIdString = "F1E1021E-A781-4862-9F4B-88746A288A67";
......@@ -109,7 +109,7 @@ internal static class Guids
public const string FSharpPackageIdString = "871D2A70-12A2-4e42-9440-425DD92A4116";
public static readonly Guid FSharpPackageId = new Guid(FSharpPackageIdString);
public static readonly Guid FSharpPackageId = new(FSharpPackageIdString);
// from vscommon\inc\textmgruuids.h
public const string TextManagerPackageString = "F5E7E720-1401-11D1-883B-0000F87579D2";
......@@ -127,13 +127,13 @@ internal static class Guids
public const string RoslynOptionPageInternalSolutionCrawlerIdString = "9702D3BD-F06C-4A6A-974B-7D0C2BC89A72";
public const string RoslynOptionPageExperimentationIdString = "D5AA7ED7-85E2-42A0-9BF6-22AEF1C1ED8C";
public static readonly Guid RoslynPackageId = new Guid(RoslynPackageIdString);
public static readonly Guid RoslynCommandSetId = new Guid(RoslynCommandSetIdString);
public static readonly Guid RoslynGroupId = new Guid(RoslynGroupIdString);
public static readonly Guid RoslynPackageId = new(RoslynPackageIdString);
public static readonly Guid RoslynCommandSetId = new(RoslynCommandSetIdString);
public static readonly Guid RoslynGroupId = new(RoslynGroupIdString);
// TODO: Remove pending https://github.com/dotnet/roslyn/issues/8927 .
// Interactive guids
public const string InteractiveCommandSetIdString = "00B8868B-F9F5-4970-A048-410B05508506";
public static readonly Guid InteractiveCommandSetId = new Guid(InteractiveCommandSetIdString);
public static readonly Guid InteractiveCommandSetId = new(InteractiveCommandSetIdString);
}
}
......@@ -17,10 +17,10 @@ internal static class InteractiveCommands
public const int ExecuteInInteractiveWindow = 0x0010C;
public const string CSharpInteractiveCommandSetIdString = "1492DB0A-85A2-4E43-BF0D-CE55B89A8CC6";
public static readonly Guid CSharpInteractiveCommandSetId = new Guid(CSharpInteractiveCommandSetIdString);
public static readonly Guid CSharpInteractiveCommandSetId = new(CSharpInteractiveCommandSetIdString);
public const string VisualBasicInteractiveCommandSetIdString = "93DF185E-D75B-4FDB-9D47-E90F111971C5";
public static readonly Guid VisualBasicInteractiveCommandSetId = new Guid(VisualBasicInteractiveCommandSetIdString);
public static readonly Guid VisualBasicInteractiveCommandSetId = new(VisualBasicInteractiveCommandSetIdString);
}
}
}
......@@ -24,7 +24,7 @@ internal sealed class AnalyzerDependencyCheckingService
/// <summary>
/// Object given as key for <see cref="HostDiagnosticUpdateSource.UpdateDiagnosticsForProject(ProjectId, object, IEnumerable{DiagnosticData})"/>.
/// </summary>
private static readonly object s_dependencyConflictErrorId = new object();
private static readonly object s_dependencyConflictErrorId = new();
private static readonly IIgnorableAssemblyList s_systemPrefixList = new IgnorableAssemblyNamePrefixList("System");
private static readonly IIgnorableAssemblyList s_codeAnalysisPrefixList = new IgnorableAssemblyNamePrefixList("Microsoft.CodeAnalysis");
private static readonly IIgnorableAssemblyList s_explicitlyIgnoredAssemblyList = new IgnorableAssemblyIdentityList(GetExplicitlyIgnoredAssemblyIdentities());
......@@ -37,8 +37,8 @@ internal sealed class AnalyzerDependencyCheckingService
/// <summary>
/// Object given to synchronize access to the mutable fields in this class.
/// </summary>
private readonly object _gate = new object();
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly object _gate = new();
private CancellationTokenSource _cancellationTokenSource = new();
/// <summary>
/// The most recently started analysis task; if we start a new analysis we will cancel the previous one and start the next one
......@@ -47,7 +47,7 @@ internal sealed class AnalyzerDependencyCheckingService
private Task _task = Task.CompletedTask;
private ImmutableHashSet<string> _previousAnalyzerPaths = ImmutableHashSet.Create<string>(StringComparer.OrdinalIgnoreCase);
private static readonly DiagnosticDescriptor s_missingAnalyzerReferenceRule = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor s_missingAnalyzerReferenceRule = new(
id: IDEDiagnosticIds.MissingAnalyzerReferenceId,
title: ServicesVSResources.MissingAnalyzerReference,
messageFormat: ServicesVSResources.Analyzer_assembly_0_depends_on_1_but_it_was_not_found_Analyzers_may_not_run_correctly_unless_the_missing_assembly_is_added_as_an_analyzer_reference_as_well,
......@@ -55,7 +55,7 @@ internal sealed class AnalyzerDependencyCheckingService
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor s_analyzerDependencyConflictRule = new DiagnosticDescriptor(
private static readonly DiagnosticDescriptor s_analyzerDependencyConflictRule = new(
id: IDEDiagnosticIds.AnalyzerDependencyConflictId,
title: ServicesVSResources.AnalyzerDependencyConflict,
messageFormat: ServicesVSResources.Analyzer_assemblies_0_and_1_both_have_identity_2_but_different_contents_Only_one_will_be_loaded_and_analyzers_using_these_assemblies_may_not_run_correctly,
......
......@@ -9,7 +9,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal sealed class AnalyzerDependencyResults
{
public static readonly AnalyzerDependencyResults Empty = new AnalyzerDependencyResults(ImmutableArray<AnalyzerDependencyConflict>.Empty, ImmutableArray<MissingAnalyzerDependency>.Empty);
public static readonly AnalyzerDependencyResults Empty = new(ImmutableArray<AnalyzerDependencyConflict>.Empty, ImmutableArray<MissingAnalyzerDependency>.Empty);
public AnalyzerDependencyResults(ImmutableArray<AnalyzerDependencyConflict> conflicts, ImmutableArray<MissingAnalyzerDependency> missingDependencies)
{
......
......@@ -23,23 +23,23 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation
[Export(typeof(AnalyzerFileWatcherService))]
internal sealed class AnalyzerFileWatcherService
{
private static readonly object s_analyzerChangedErrorId = new object();
private static readonly object s_analyzerChangedErrorId = new();
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly HostDiagnosticUpdateSource _updateSource;
private readonly IVsFileChangeEx _fileChangeService;
private readonly Dictionary<string, FileChangeTracker> _fileChangeTrackers = new Dictionary<string, FileChangeTracker>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, FileChangeTracker> _fileChangeTrackers = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Holds a list of assembly modified times that we can use to detect a file change prior to the <see cref="FileChangeTracker"/> being in place.
/// Once it's in place and subscribed, we'll remove the entry because any further changes will be detected that way.
/// </summary>
private readonly Dictionary<string, DateTime> _assemblyUpdatedTimesUtc = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DateTime> _assemblyUpdatedTimesUtc = new(StringComparer.OrdinalIgnoreCase);
private readonly object _guard = new object();
private readonly object _guard = new();
private readonly DiagnosticDescriptor _analyzerChangedRule = new DiagnosticDescriptor(
private readonly DiagnosticDescriptor _analyzerChangedRule = new(
id: IDEDiagnosticIds.AnalyzerChangedId,
title: ServicesVSResources.AnalyzerChangedOnDisk,
messageFormat: ServicesVSResources.The_analyzer_assembly_0_has_changed_Diagnostics_may_be_incorrect_until_Visual_Studio_is_restarted,
......
......@@ -42,7 +42,7 @@ public CallHierarchyItem(ISymbol symbol, ProjectId projectId, IEnumerable<Abstra
}
public static readonly SymbolDisplayFormat MemberNameFormat =
new SymbolDisplayFormat(
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
......@@ -56,7 +56,7 @@ public CallHierarchyItem(ISymbol symbol, ProjectId projectId, IEnumerable<Abstra
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
public static readonly SymbolDisplayFormat ContainingTypeFormat =
new SymbolDisplayFormat(
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
......@@ -64,7 +64,7 @@ public CallHierarchyItem(ISymbol symbol, ProjectId projectId, IEnumerable<Abstra
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
public static readonly SymbolDisplayFormat ContainingNamespaceFormat =
new SymbolDisplayFormat(
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
private readonly Workspace _workspace;
......
......@@ -19,7 +19,7 @@ namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
internal abstract class AbstractCallFinder
{
private readonly IAsynchronousOperationListener _asyncListener;
private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource();
private readonly CancellationTokenSource _cancellationSource = new();
private readonly ProjectId _projectId;
private readonly SymbolKey _symbolKey;
......
......@@ -71,7 +71,7 @@ private void Cancel_Click(object sender, RoutedEventArgs e)
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
=> new(this);
internal readonly struct TestAccessor
{
......
......@@ -52,7 +52,7 @@ public AddParameterDialogViewModel(Document document, int positionForTypeBinding
public string CallSiteValue { get; set; }
private static readonly SymbolDisplayFormat s_symbolDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_symbolDisplayFormat = new(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
......
......@@ -276,7 +276,7 @@ private void ToggleRemovedState(object sender, ExecutedRoutedEventArgs e)
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
=> new(this);
internal readonly struct TestAccessor
{
......
......@@ -38,7 +38,7 @@ internal partial class ChangeSignatureDialogViewModel : AbstractNotifyPropertyCh
// This can be changed to ParameterViewModel if we will allow adding 'params' parameter.
private readonly ExistingParameterViewModel? _paramsParameter;
private readonly HashSet<ParameterViewModel> _disabledParameters = new HashSet<ParameterViewModel>();
private readonly HashSet<ParameterViewModel> _disabledParameters = new();
private ImmutableArray<SymbolDisplayPart> _declarationParts;
private bool _previewChanges;
......@@ -145,7 +145,7 @@ private void UpdateNameConflictMarkers()
}
public AddParameterDialogViewModel CreateAddParameterDialogViewModel()
=> new AddParameterDialogViewModel(_document, _positionForTypeBinding);
=> new(_document, _positionForTypeBinding);
private List<ParameterViewModel> CreateParameterViewModels(ImmutableArray<Parameter> parameters, ref int initialIndex)
{
......@@ -304,7 +304,7 @@ internal ParameterConfiguration GetParameterConfiguration()
selectedIndex: -1);
}
private static readonly SymbolDisplayFormat s_symbolDeclarationDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_symbolDeclarationDisplayFormat = new(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
......@@ -318,7 +318,7 @@ internal ParameterConfiguration GetParameterConfiguration()
SymbolDisplayMemberOptions.IncludeModifiers |
SymbolDisplayMemberOptions.IncludeRef);
private static readonly SymbolDisplayFormat s_parameterDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_parameterDisplayFormat = new(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
......
......@@ -27,7 +27,7 @@ private sealed class ClassificationVerifier : ForegroundThreadAffinitizedObject
private readonly IServiceProvider _serviceProvider;
private readonly ImmutableDictionary<SchemeName, ImmutableDictionary<Guid, ImmutableDictionary<string, uint>>> _colorSchemes;
private static readonly Guid TextEditorMEFItemsColorCategory = new Guid("75a05685-00a8-4ded-bae5-e7a50bfa929a");
private static readonly Guid TextEditorMEFItemsColorCategory = new("75a05685-00a8-4ded-bae5-e7a50bfa929a");
// These classification colors (0x00BBGGRR) should match the VS\EditorColors.xml file.
// They are not in the scheme files because they are core classifications.
......
......@@ -20,7 +20,7 @@ internal partial class ColorSchemeApplier
{
private static class ColorSchemeReader
{
private static readonly XmlReaderSettings s_xmlSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit };
private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit };
private const string RawColorType = nameof(__VSCOLORTYPE.CT_RAW);
private const string SystemColorType = nameof(__VSCOLORTYPE.CT_SYSCOLOR);
......
......@@ -20,7 +20,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation
[Export(typeof(IRefactorNotifyService))]
internal sealed class ContainedLanguageRefactorNotifyService : IRefactorNotifyService
{
private static readonly SymbolDisplayFormat s_qualifiedDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_qualifiedDisplayFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
......
......@@ -20,7 +20,7 @@ internal partial class DebuggerTextView
{
// HACK HACK HACK HACK HACK: We'll use this fake ICompletionSession to trick them into
// routing commands to us for both completion and sighelp
private readonly HACK_CompletionSession _hackCompletionSession = new HACK_CompletionSession();
private readonly HACK_CompletionSession _hackCompletionSession = new();
public void HACK_StartCompletionSession(IIntellisenseSession editorSessionOpt)
{
......
......@@ -52,7 +52,7 @@ internal class VisualStudioDesignerAttributeService
/// that project.
/// </summary>
private readonly ConcurrentDictionary<ProjectId, IProjectItemDesignerTypeUpdateService?> _cpsProjects
= new ConcurrentDictionary<ProjectId, IProjectItemDesignerTypeUpdateService?>();
= new();
/// <summary>
/// Cached designer service for notifying legacy projects about designer attributes.
......
......@@ -30,7 +30,7 @@ internal sealed class TaskCenterSolutionAnalysisProgressReporter
/// Gate access to reporting sln crawler events so we cannot
/// report UI changes concurrently.
/// </summary>
private readonly object _lock = new object();
private readonly object _lock = new();
/// <summary>
/// Task used to trigger throttled UI updates in an interval
......
......@@ -13,10 +13,10 @@ internal static class DebuggerComponent
/// <summary>
/// Component id as specified in ManagedEditAndContinueService.vsdconfigxml.
/// </summary>
private static readonly Guid ManagedEditAndContinueServiceId = new Guid("A96BBE03-0408-41E3-8613-6086FD494B43");
private static readonly Guid ManagedEditAndContinueServiceId = new("A96BBE03-0408-41E3-8613-6086FD494B43");
public static ThreadInitializer ManagedEditAndContinueService()
=> new ThreadInitializer(ManagedEditAndContinueServiceId);
=> new(ManagedEditAndContinueServiceId);
public struct ThreadInitializer : IDisposable
{
......
......@@ -77,14 +77,14 @@ internal static LinePositionSpan ToLinePositionSpan(this DkmTextSpan span)
}
internal static DkmTextSpan ToDebuggerSpan(this LinePositionSpan span, int lineDelta = 0)
=> new DkmTextSpan(
=> new(
StartLine: span.Start.Line + lineDelta + 1,
EndLine: span.End.Line + lineDelta + 1,
StartColumn: span.Start.Character + 1,
EndColumn: span.End.Character + 1);
internal static EnC.ActiveStatementDebugInfo ToActiveStatementDebugInfo(this ActiveStatementDebugInfo info)
=> new EnC.ActiveStatementDebugInfo(
=> new(
new EnC.ActiveInstructionId(info.InstructionId.MethodId.ModuleId, info.InstructionId.MethodId.Token, info.InstructionId.MethodId.Version, info.InstructionId.ILOffset),
info.DocumentNameOpt,
info.TextSpan.ToLinePositionSpan(),
......@@ -125,7 +125,7 @@ internal static DkmManagedModuleUpdate ToModuleUpdate(this EnC.Deltas delta)
}
internal static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this ImmutableArray<T> array)
=> new ReadOnlyCollection<T>(array.DangerousGetUnderlyingArray());
=> new(array.DangerousGetUnderlyingArray());
internal static ManagedModuleUpdateStatus ToModuleUpdateStatus(this EnC.SolutionUpdateStatus status)
=> status switch
......
......@@ -34,7 +34,7 @@ private sealed class DebuggerService : IDkmCustomMessageForwardReceiver
/// <summary>
/// Message source id as specified in ManagedEditAndContinueService.vsdconfigxml.
/// </summary>
public static readonly Guid MessageSourceId = new Guid("58CDF976-1923-48F7-8288-B4189F5700B1");
public static readonly Guid MessageSourceId = new("58CDF976-1923-48F7-8288-B4189F5700B1");
private sealed class DataItem : DkmDataItem
{
......
......@@ -38,7 +38,7 @@ public VisualStudioManagedModuleUpdateProvider(VisualStudioWorkspace workspace)
}
private SolutionActiveStatementSpanProvider GetActiveStatementSpanProvider(Solution solution)
=> new SolutionActiveStatementSpanProvider((documentId, cancellationToken) =>
=> new((documentId, cancellationToken) =>
_activeStatementTrackingService.GetSpansAsync(solution.GetRequiredDocument(documentId), cancellationToken));
/// <summary>
......
......@@ -56,8 +56,8 @@ internal sealed class KeybindingResetDetector : ForegroundThreadAffinitizedObjec
private const uint ResumeId = 707;
private const uint SuspendId = 708;
private const uint ToggleSuspendId = 709;
private static readonly Guid ReSharperPackageGuid = new Guid("0C6E6407-13FC-4878-869A-C8B4016C57FE");
private static readonly Guid ReSharperCommandGroup = new Guid("{47F03277-5055-4922-899C-0F7F30D26BF1}");
private static readonly Guid ReSharperPackageGuid = new("0C6E6407-13FC-4878-869A-C8B4016C57FE");
private static readonly Guid ReSharperCommandGroup = new("{47F03277-5055-4922-899C-0F7F30D26BF1}");
private readonly VisualStudioWorkspace _workspace;
private readonly System.IServiceProvider _serviceProvider;
......@@ -70,7 +70,7 @@ internal sealed class KeybindingResetDetector : ForegroundThreadAffinitizedObjec
private OleComponent _oleComponent;
private uint _priorityCommandTargetCookie = VSConstants.VSCOOKIE_NIL;
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private CancellationTokenSource _cancellationTokenSource = new();
/// <summary>
/// If false, ReSharper is either not installed, or has been disabled in the extension manager.
/// If true, the ReSharper extension is enabled. ReSharper's internal status could be either suspended or enabled.
......
......@@ -10,15 +10,15 @@ internal static class KeybindingResetOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\KeybindingsStatus\";
public static readonly Option<ReSharperStatus> ReSharperStatus = new Option<ReSharperStatus>(nameof(KeybindingResetOptions),
public static readonly Option<ReSharperStatus> ReSharperStatus = new(nameof(KeybindingResetOptions),
nameof(ReSharperStatus), defaultValue: Experimentation.ReSharperStatus.NotInstalledOrDisabled,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(ReSharperStatus)));
public static readonly Option<bool> NeedsReset = new Option<bool>(nameof(KeybindingResetOptions),
public static readonly Option<bool> NeedsReset = new(nameof(KeybindingResetOptions),
nameof(NeedsReset), defaultValue: false,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeedsReset)));
public static readonly Option<bool> NeverShowAgain = new Option<bool>(nameof(KeybindingResetOptions),
public static readonly Option<bool> NeverShowAgain = new(nameof(KeybindingResetOptions),
nameof(NeverShowAgain), defaultValue: false,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeverShowAgain)));
}
......
......@@ -19,7 +19,7 @@ internal static class VisualStudioWorkspaceImplExtensions
// hierarchy we're getting them for. To do this, we attach them to the hierarchy with a
// conditional weak table.
private static readonly ConditionalWeakTable<IVsHierarchy, Dictionary<uint, IImageHandle>> s_hierarchyToItemIdToImageHandle =
new ConditionalWeakTable<IVsHierarchy, Dictionary<uint, IImageHandle>>();
new();
private static readonly ConditionalWeakTable<IVsHierarchy, Dictionary<uint, IImageHandle>>.CreateValueCallback s_createValue =
_ => new Dictionary<uint, IImageHandle>();
......
......@@ -111,7 +111,7 @@ private void ToggleCheckSelection()
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
=> new(this);
internal readonly struct TestAccessor
{
......
......@@ -16,7 +16,7 @@ internal abstract class AbstractHelpContextService : IHelpContextService
// C`1.M``2
// constructors: Parent.Type.#ctor
protected static readonly SymbolDisplayFormat TypeFormat =
new SymbolDisplayFormat(
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
......@@ -24,7 +24,7 @@ internal abstract class AbstractHelpContextService : IHelpContextService
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
protected static readonly SymbolDisplayFormat SpecialTypeFormat =
new SymbolDisplayFormat(
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
genericsOptions: SymbolDisplayGenericsOptions.None,
......@@ -33,7 +33,7 @@ internal abstract class AbstractHelpContextService : IHelpContextService
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
protected static readonly SymbolDisplayFormat NameFormat =
new SymbolDisplayFormat(
new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
......
......@@ -29,7 +29,7 @@ internal partial class StreamingFindUsagesPresenter
private abstract class AbstractTableDataSourceFindUsagesContext :
FindUsagesContext, ITableDataSource, ITableEntriesSnapshotFactory
{
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly CancellationTokenSource _cancellationTokenSource = new();
private ITableDataSink _tableDataSink;
......@@ -39,7 +39,7 @@ private abstract class AbstractTableDataSourceFindUsagesContext :
private readonly AsyncBatchingWorkQueue<(int current, int maximum)> _progressQueue;
protected readonly object Gate = new object();
protected readonly object Gate = new();
#region Fields that should be locked by _gate
......@@ -56,7 +56,7 @@ private abstract class AbstractTableDataSourceFindUsagesContext :
/// us to not display it if it has no references, and we don't run into any
/// references for it (common with implicitly declared symbols).
/// </summary>
protected readonly List<DefinitionItem> Definitions = new List<DefinitionItem>();
protected readonly List<DefinitionItem> Definitions = new();
/// <summary>
/// We will hear about the same definition over and over again. i.e. for each reference
......@@ -67,7 +67,7 @@ private abstract class AbstractTableDataSourceFindUsagesContext :
/// and then always return that for all future references found.
/// </summary>
private readonly Dictionary<DefinitionItem, RoslynDefinitionBucket> _definitionToBucket =
new Dictionary<DefinitionItem, RoslynDefinitionBucket>();
new();
/// <summary>
/// We want to hide declarations of a symbol if the user is grouping by definition.
......
......@@ -21,7 +21,7 @@ internal static class FindUsagesOptions
/// and we want to restore the value back to its original state when the user does the
/// next FindReferences call.
/// </summary>
public static readonly Option<int> DefinitionGroupingPriority = new Option<int>(
public static readonly Option<int> DefinitionGroupingPriority = new(
nameof(FindUsagesOptions), nameof(DefinitionGroupingPriority), defaultValue: -1,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(DefinitionGroupingPriority)));
}
......
......@@ -42,7 +42,7 @@ internal partial class StreamingFindUsagesPresenter :
private readonly Workspace _workspace;
private readonly HashSet<AbstractTableDataSourceFindUsagesContext> _currentContexts =
new HashSet<AbstractTableDataSourceFindUsagesContext>();
new();
private readonly ImmutableArray<ITableColumnDefinition> _customColumns;
[ImportingConstructor]
......
......@@ -110,7 +110,7 @@ private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
=> new(this);
internal readonly struct TestAccessor
{
......
......@@ -24,6 +24,6 @@ internal sealed class CSharpResetInteractiveMenuCommand
protected override string ProjectKind => VSLangProj.PrjKind.prjKindCSharpProject;
protected override CommandID GetResetInteractiveFromProjectCommandID()
=> new CommandID(ID.InteractiveCommands.CSharpInteractiveCommandSetId, ID.InteractiveCommands.ResetInteractiveFromProject);
=> new(ID.InteractiveCommands.CSharpInteractiveCommandSetId, ID.InteractiveCommands.ResetInteractiveFromProject);
}
}
......@@ -24,6 +24,6 @@ internal sealed class VisualBasicResetInteractiveMenuCommand
protected override string ProjectKind => VSLangProj.PrjKind.prjKindVBProject;
protected override CommandID GetResetInteractiveFromProjectCommandID()
=> new CommandID(ID.InteractiveCommands.VisualBasicInteractiveCommandSetId, ID.InteractiveCommands.ResetInteractiveFromProject);
=> new(ID.InteractiveCommands.VisualBasicInteractiveCommandSetId, ID.InteractiveCommands.ResetInteractiveFromProject);
}
}
......@@ -332,7 +332,7 @@ private void RequestExecutionQueue_Errored(object sender, RequestShutdownEventAr
/// union the currently computed diagnostics (e.g. for dA) with previously computed diagnostics (e.g. from dB).
/// </summary>
private readonly Dictionary<Uri, Dictionary<DocumentId, ImmutableArray<LanguageServer.Protocol.Diagnostic>>> _publishedFileToDiagnostics =
new Dictionary<Uri, Dictionary<DocumentId, ImmutableArray<LanguageServer.Protocol.Diagnostic>>>();
new();
/// <summary>
/// Stores the mapping of a document to the uri(s) of diagnostics previously produced for this document.
......@@ -342,7 +342,7 @@ private void RequestExecutionQueue_Errored(object sender, RequestShutdownEventAr
/// While it's not necessary to publish a document's mapped file diagnostics in a particular order,
/// it does make it much easier to write tests and debug issues if we have a consistent ordering.
/// </summary>
private readonly Dictionary<DocumentId, ImmutableSortedSet<Uri>> _documentsToPublishedUris = new Dictionary<DocumentId, ImmutableSortedSet<Uri>>();
private readonly Dictionary<DocumentId, ImmutableSortedSet<Uri>> _documentsToPublishedUris = new();
/// <summary>
/// Basic comparer for Uris used by <see cref="_documentsToPublishedUris"/> when publishing notifications.
......@@ -483,7 +483,7 @@ static LanguageServer.Protocol.Diagnostic ConvertToLspDiagnostic(DiagnosticData
return ProtocolConversions.LinePositionToRange(linePositionSpan);
}
internal TestAccessor GetTestAccessor() => new TestAccessor(this);
internal TestAccessor GetTestAccessor() => new(this);
internal readonly struct TestAccessor
{
......
......@@ -18,7 +18,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsImmediateStatementCompletion2
{
protected Dictionary<IVsTextView, DebuggerIntelliSenseFilter> filters =
new Dictionary<IVsTextView, DebuggerIntelliSenseFilter>();
new();
int IVsImmediateStatementCompletion2.EnableStatementCompletion(int enable, int startIndex, int endIndex, IVsTextView textView)
{
......
......@@ -20,7 +20,7 @@ internal abstract partial class AbstractDescriptionBuilder
private readonly ObjectListItem _listItem;
private readonly Project _project;
private static readonly SymbolDisplayFormat s_typeDisplay = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_typeDisplay = new(
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
protected AbstractDescriptionBuilder(
......
......@@ -21,34 +21,34 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectB
internal abstract class AbstractListItemFactory
{
private static readonly SymbolDisplayFormat s_searchFormat =
new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
new(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly);
private static readonly SymbolDisplayFormat s_simplePredefinedTypeDisplay =
new SymbolDisplayFormat(
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes);
private static readonly SymbolDisplayFormat s_simpleNormalTypeDisplay =
new SymbolDisplayFormat(
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static readonly SymbolDisplayFormat s_simplePredefinedTypeFullName =
new SymbolDisplayFormat(
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
private static readonly SymbolDisplayFormat s_simpleNormalTypeFullName =
new SymbolDisplayFormat(
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private static readonly SymbolDisplayFormat s_predefinedTypeDisplay =
new SymbolDisplayFormat(
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces);
private static readonly SymbolDisplayFormat s_normalTypeDisplay =
new SymbolDisplayFormat(
new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
......
......@@ -36,7 +36,7 @@ internal abstract partial class AbstractObjectBrowserLibraryManager : AbstractLi
private ObjectListItem _activeListItem;
private AbstractListItemFactory _listItemFactory;
private readonly object _classMemberGate = new object();
private readonly object _classMemberGate = new();
private readonly IStreamingFindUsagesPresenter _streamingPresenter;
......
......@@ -12,11 +12,11 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectB
{
internal static class Extensions
{
private static readonly SymbolDisplayFormat s_typeDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_typeDisplayFormat = new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance);
private static readonly SymbolDisplayFormat s_memberDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_memberDisplayFormat = new(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance,
memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeParameters,
......
......@@ -15,13 +15,13 @@ internal static class LoggerOptions
{
private const string LocalRegistryPath = @"Roslyn\Internal\Performance\Logger\";
public static readonly Option<bool> EtwLoggerKey = new Option<bool>(nameof(LoggerOptions), nameof(EtwLoggerKey), defaultValue: true,
public static readonly Option<bool> EtwLoggerKey = new(nameof(LoggerOptions), nameof(EtwLoggerKey), defaultValue: true,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "EtwLogger"));
public static readonly Option<bool> TraceLoggerKey = new Option<bool>(nameof(LoggerOptions), nameof(TraceLoggerKey), defaultValue: false,
public static readonly Option<bool> TraceLoggerKey = new(nameof(LoggerOptions), nameof(TraceLoggerKey), defaultValue: false,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "TraceLogger"));
public static readonly Option<bool> OutputWindowLoggerKey = new Option<bool>(nameof(LoggerOptions), nameof(OutputWindowLoggerKey), defaultValue: false,
public static readonly Option<bool> OutputWindowLoggerKey = new(nameof(LoggerOptions), nameof(OutputWindowLoggerKey), defaultValue: false,
storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + "OutputWindowLogger"));
}
......
......@@ -37,7 +37,7 @@ internal MoveToNamespaceDialog(MoveToNamespaceDialogViewModel viewModel)
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
internal TestAccessor GetTestAccessor() => new TestAccessor(this);
internal TestAccessor GetTestAccessor() => new(this);
private void OK_Click(object sender, RoutedEventArgs e)
{
......
......@@ -20,7 +20,7 @@ internal class VisualStudioMoveToNamespaceOptionsService : IMoveToNamespaceOptio
{
private const int HistorySize = 3;
public readonly LinkedList<string> History = new LinkedList<string>();
public readonly LinkedList<string> History = new();
private readonly Func<MoveToNamespaceDialogViewModel, bool?> _showDialog;
[ImportingConstructor]
......
......@@ -15,7 +15,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.NavigateTo
internal sealed class VisualStudioNavigateToPreviewServiceFactory : IWorkspaceServiceFactory
{
private readonly Lazy<INavigateToPreviewService> _singleton =
new Lazy<INavigateToPreviewService>(() => new VisualStudioNavigateToPreviewService());
new(() => new VisualStudioNavigateToPreviewService());
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
......
......@@ -35,7 +35,7 @@ internal class NavigationBarClient :
private readonly ComEventSink _codeWindowEventsSink;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService;
private readonly IVsImageService2 _imageService;
private readonly Dictionary<IVsTextView, ITextView> _trackedTextViews = new Dictionary<IVsTextView, ITextView>();
private readonly Dictionary<IVsTextView, ITextView> _trackedTextViews = new();
private IVsDropdownBar _dropdownBar;
private IList<NavigationBarProjectItem> _projectItems;
private IList<NavigationBarItem> _currentTypeItems;
......
......@@ -19,7 +19,7 @@ internal class VSNotificationServiceFactory : IWorkspaceServiceFactory
{
private readonly IVsUIShell _uiShellService;
private static readonly object s_gate = new object();
private static readonly object s_gate = new();
private static VSDialogService s_singleton;
......
......@@ -25,7 +25,7 @@ internal sealed class LocalUserRegistryOptionPersister : IOptionPersister
/// <summary>
/// An object to gate access to <see cref="_registryKey"/>.
/// </summary>
private readonly object _gate = new object();
private readonly object _gate = new();
private readonly RegistryKey _registryKey;
[ImportingConstructor]
......
......@@ -41,8 +41,8 @@ private class SVsSettingsPersistenceManager { };
/// if a later change happens, we know to refresh that value. This is synchronized with monitor locks on
/// <see cref="_optionsToMonitorForChangesGate" />.
/// </summary>
private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new Dictionary<string, List<OptionKey>>();
private readonly object _optionsToMonitorForChangesGate = new object();
private readonly Dictionary<string, List<OptionKey>> _optionsToMonitorForChanges = new();
private readonly object _optionsToMonitorForChangesGate = new();
/// <remarks>
/// We make sure this code is from the UI by asking for all <see cref="IOptionPersister"/> in <see cref="RoslynPackage.InitializeAsync"/>
......
......@@ -137,7 +137,7 @@ private void ToggleCheckSelection()
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
=> new(this);
internal readonly struct TestAccessor
{
......
......@@ -9,7 +9,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview
{
internal partial class ChangeList : IVsPreviewChangesList, IVsLiteTreeList
{
public static readonly ChangeList Empty = new ChangeList(Array.Empty<AbstractChange>());
public static readonly ChangeList Empty = new(Array.Empty<AbstractChange>());
internal AbstractChange[] Changes { get; }
......
......@@ -23,7 +23,7 @@ internal partial class PreviewPane : UserControl, IDisposable
private const double DefaultWidth = 400;
private static readonly string s_dummyThreeLineTitle = "A" + Environment.NewLine + "A" + Environment.NewLine + "A";
private static readonly Size s_infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
private static readonly Size s_infiniteSize = new(double.PositiveInfinity, double.PositiveInfinity);
private readonly string _id;
private readonly bool _logIdVerbatimInTelemetry;
......
......@@ -25,17 +25,17 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed partial class GraphBuilder
{
private readonly Graph _graph = new Graph();
private readonly SemaphoreSlim _gate = new SemaphoreSlim(initialCount: 1);
private readonly Graph _graph = new();
private readonly SemaphoreSlim _gate = new(initialCount: 1);
private readonly ISet<GraphNode> _createdNodes = new HashSet<GraphNode>();
private readonly IList<Tuple<GraphNode, GraphProperty, object>> _deferredPropertySets = new List<Tuple<GraphNode, GraphProperty, object>>();
private readonly CancellationToken _cancellationToken;
private readonly Dictionary<GraphNode, Project> _nodeToContextProjectMap = new Dictionary<GraphNode, Project>();
private readonly Dictionary<GraphNode, Document> _nodeToContextDocumentMap = new Dictionary<GraphNode, Document>();
private readonly Dictionary<GraphNode, ISymbol> _nodeToSymbolMap = new Dictionary<GraphNode, ISymbol>();
private readonly Dictionary<GraphNode, Project> _nodeToContextProjectMap = new();
private readonly Dictionary<GraphNode, Document> _nodeToContextDocumentMap = new();
private readonly Dictionary<GraphNode, ISymbol> _nodeToSymbolMap = new();
/// <summary>
/// The input solution. Never null.
......
......@@ -327,16 +327,16 @@ private bool IsAnyTypeKind(GraphNode node, params TypeKind[] typeKinds)
=> typeKinds.Any(k => node[RoslynGraphProperties.TypeKind].Equals(k));
private static readonly GraphCommandDefinition s_overridesCommandDefinition =
new GraphCommandDefinition("Overrides", ServicesVSResources.Overrides_, GraphContextDirection.Target, 700);
new("Overrides", ServicesVSResources.Overrides_, GraphContextDirection.Target, 700);
private static readonly GraphCommandDefinition s_overriddenByCommandDefinition =
new GraphCommandDefinition("OverriddenBy", ServicesVSResources.Overridden_By, GraphContextDirection.Source, 700);
new("OverriddenBy", ServicesVSResources.Overridden_By, GraphContextDirection.Source, 700);
private static readonly GraphCommandDefinition s_implementsCommandDefinition =
new GraphCommandDefinition("Implements", ServicesVSResources.Implements_, GraphContextDirection.Target, 600);
new("Implements", ServicesVSResources.Implements_, GraphContextDirection.Target, 600);
private static readonly GraphCommandDefinition s_implementedByCommandDefinition =
new GraphCommandDefinition("ImplementedBy", ServicesVSResources.Implemented_By, GraphContextDirection.Source, 600);
new("ImplementedBy", ServicesVSResources.Implemented_By, GraphContextDirection.Source, 600);
public T GetExtension<T>(GraphObject graphObject, T previous) where T : class
{
......
......@@ -28,8 +28,8 @@ internal class GraphQueryManager
/// <summary>
/// This gate locks manipulation of <see cref="_trackedQueries"/>.
/// </summary>
private readonly object _gate = new object();
private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>>();
private readonly object _gate = new();
private readonly List<ValueTuple<WeakReference<IGraphContext>, List<IGraphQuery>>> _trackedQueries = new();
// We update all of our tracked queries when this delay elapses.
private ResettableDelay? _delay;
......
......@@ -18,7 +18,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectInfoServ
internal sealed class DefaultProjectInfoServiceFactory : IWorkspaceServiceFactory
{
private readonly Lazy<IProjectInfoService> _singleton =
new Lazy<IProjectInfoService>(() => new DefaultProjectInfoService());
new(() => new DefaultProjectInfoService());
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
......
......@@ -13,7 +13,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
{
internal abstract class AbstractEntryPointFinder : SymbolVisitor
{
protected readonly HashSet<INamedTypeSymbol> EntryPoints = new HashSet<INamedTypeSymbol>();
protected readonly HashSet<INamedTypeSymbol> EntryPoints = new();
public override void VisitNamespace(INamespaceSymbol symbol)
{
......
......@@ -27,7 +27,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
internal partial class AnalyzerConfigDocumentAsSolutionItemHandler : IDisposable
{
private static readonly string LocalRegistryPath = $@"Roslyn\Internal\{nameof(AnalyzerConfigDocumentAsSolutionItemHandler)}\";
private static readonly Option<bool> NeverShowAgain = new Option<bool>(nameof(AnalyzerConfigDocumentAsSolutionItemHandler), nameof(NeverShowAgain),
private static readonly Option<bool> NeverShowAgain = new(nameof(AnalyzerConfigDocumentAsSolutionItemHandler), nameof(NeverShowAgain),
defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(NeverShowAgain)));
private readonly VisualStudioWorkspace _workspace;
......
......@@ -18,7 +18,7 @@ internal sealed class FileChangeTracker : IVsFreeThreadedFileChangeEvents2, IDis
{
private const _VSFILECHANGEFLAGS DefaultFileChangeFlags = _VSFILECHANGEFLAGS.VSFILECHG_Time | _VSFILECHANGEFLAGS.VSFILECHG_Add | _VSFILECHANGEFLAGS.VSFILECHG_Del | _VSFILECHANGEFLAGS.VSFILECHG_Size;
private static readonly AsyncLazy<uint?> s_none = new AsyncLazy<uint?>(value: null);
private static readonly AsyncLazy<uint?> s_none = new(value: null);
private readonly IVsFileChangeEx _fileChangeService;
private readonly string _filePath;
......@@ -49,7 +49,7 @@ internal sealed class FileChangeTracker : IVsFreeThreadedFileChangeEvents2, IDis
/// and easy to delete if this lock has contention itself. Given we tend to call <see cref="StartFileChangeListeningAsync"/> on the UI
/// thread, I don't expect to see contention.
/// </summary>
private static readonly object s_lastBackgroundTaskGate = new object();
private static readonly object s_lastBackgroundTaskGate = new();
public FileChangeTracker(IVsFileChangeEx fileChangeService, string filePath, _VSFILECHANGEFLAGS fileChangeFlags = DefaultFileChangeFlags)
{
......
......@@ -27,7 +27,7 @@ internal sealed class FileChangeWatcher
/// <summary>
/// Gate that is used to guard modifications to <see cref="_taskQueue"/>.
/// </summary>
private readonly object _taskQueueGate = new object();
private readonly object _taskQueueGate = new();
/// <summary>
/// We create a queue of tasks against the IVsFileChangeEx service for two reasons. First, we are obtaining the service asynchronously, and don't want to
......@@ -160,9 +160,9 @@ private sealed class Context : IVsFreeThreadedFileChangeEvents2, IContext
/// <summary>
/// Gate to guard mutable fields in this class and any mutation of any <see cref="FileWatchingToken"/>s.
/// </summary>
private readonly object _gate = new object();
private readonly object _gate = new();
private bool _disposed = false;
private readonly HashSet<FileWatchingToken> _activeFileWatchingTokens = new HashSet<FileWatchingToken>();
private readonly HashSet<FileWatchingToken> _activeFileWatchingTokens = new();
/// <summary>
/// The list of cookies we used to make watchers for <see cref="_watchedDirectories"/>.
......@@ -171,7 +171,7 @@ private sealed class Context : IVsFreeThreadedFileChangeEvents2, IContext
/// This does not need to be used under <see cref="_gate"/>, as it's only used inside the actual queue of file watcher
/// actions.
/// </remarks>
private readonly List<uint> _directoryWatchCookies = new List<uint>();
private readonly List<uint> _directoryWatchCookies = new();
public Context(FileChangeWatcher fileChangeWatcher, ImmutableArray<WatchedDirectory> watchedDirectories)
{
......
......@@ -18,7 +18,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
[Export(typeof(FileChangeWatcherProvider))]
internal sealed class FileChangeWatcherProvider
{
private readonly TaskCompletionSource<IVsAsyncFileChangeEx> _fileChangeService = new TaskCompletionSource<IVsAsyncFileChangeEx>(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<IVsAsyncFileChangeEx> _fileChangeService = new(TaskCreationOptions.RunContinuationsAsynchronously);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
......
......@@ -304,7 +304,7 @@ private static Guid GetProjectIDGuid(IVsHierarchy hierarchy)
/// </summary>
/// <remarks>Using item IDs as a key like this in a long-lived way is considered unsupported by CPS and other
/// IVsHierarchy providers, but this code (which is fairly old) still makes the assumptions anyways.</remarks>
private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new Dictionary<uint, ImmutableArray<string>>();
private readonly Dictionary<uint, ImmutableArray<string>> _folderNameMap = new();
private ImmutableArray<string> GetFolderNamesForDocument(uint documentItemID)
{
......
......@@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.L
{
internal abstract partial class AbstractLegacyProject : IProjectSiteEx
{
private readonly Stack<VisualStudioProject.BatchScope> _batchScopes = new Stack<VisualStudioProject.BatchScope>();
private readonly Stack<VisualStudioProject.BatchScope> _batchScopes = new();
public void StartBatch()
=> _batchScopes.Push(VisualStudioProject.CreateBatchScope());
......
......@@ -18,7 +18,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.M
[Export]
internal sealed class FileWatchedPortableExecutableReferenceFactory
{
private readonly object _gate = new object();
private readonly object _gate = new();
/// <summary>
/// This right now acquires the entire VisualStudioWorkspace because right now the production
......@@ -37,14 +37,14 @@ internal sealed class FileWatchedPortableExecutableReferenceFactory
/// File watching tokens from <see cref="_fileReferenceChangeContext"/> that are watching metadata references. These are only created once we are actually applying a batch because
/// we don't determine until the batch is applied if the file reference will actually be a file reference or it'll be a converted project reference.
/// </summary>
private readonly Dictionary<PortableExecutableReference, FileChangeWatcher.IFileWatchingToken> _metadataReferenceFileWatchingTokens = new Dictionary<PortableExecutableReference, FileChangeWatcher.IFileWatchingToken>();
private readonly Dictionary<PortableExecutableReference, FileChangeWatcher.IFileWatchingToken> _metadataReferenceFileWatchingTokens = new();
/// <summary>
/// <see cref="CancellationTokenSource"/>s for in-flight refreshing of metadata references. When we see a file change, we wait a bit before trying to actually
/// update the workspace. We need cancellation tokens for those so we can cancel them either when a flurry of events come in (so we only do the delay after the last
/// modification), or when we know the project is going away entirely.
/// </summary>
private readonly Dictionary<string, CancellationTokenSource> _metadataReferenceRefreshCancellationTokenSources = new Dictionary<string, CancellationTokenSource>();
private readonly Dictionary<string, CancellationTokenSource> _metadataReferenceRefreshCancellationTokenSources = new();
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
......
......@@ -18,10 +18,10 @@ private sealed class MetadataCache
private const int InitialCapacity = 64;
private const int CapacityMultiplier = 2;
private readonly object _gate = new object();
private readonly object _gate = new();
// value is ValueSource so that how metadata is re-acquired back are different per entry.
private readonly Dictionary<FileKey, ValueSource<Optional<AssemblyMetadata>>> _metadataCache = new Dictionary<FileKey, ValueSource<Optional<AssemblyMetadata>>>();
private readonly Dictionary<FileKey, ValueSource<Optional<AssemblyMetadata>>> _metadataCache = new();
private int _capacity = InitialCapacity;
......
......@@ -33,8 +33,8 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
/// </remarks>
internal sealed partial class VisualStudioMetadataReferenceManager : IWorkspaceService
{
private static readonly Guid s_IID_IMetaDataImport = new Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44");
private static readonly ConditionalWeakTable<Metadata, object> s_lifetimeMap = new ConditionalWeakTable<Metadata, object>();
private static readonly Guid s_IID_IMetaDataImport = new("7DAC8207-D3AE-4c75-9B67-92801A497D44");
private static readonly ConditionalWeakTable<Metadata, object> s_lifetimeMap = new();
private readonly MetadataCache _metadataCache;
private readonly ImmutableArray<string> _runtimeDirectories;
......@@ -52,7 +52,7 @@ internal sealed partial class VisualStudioMetadataReferenceManager : IWorkspaceS
internal IVsFileChangeEx FileChangeService { get; }
private readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim();
private readonly ReaderWriterLockSlim _readerWriterLock = new();
internal VisualStudioMetadataReferenceManager(IServiceProvider serviceProvider, ITemporaryStorageService temporaryStorageService)
{
......
......@@ -34,7 +34,7 @@ internal sealed partial class MiscellaneousFilesWorkspace : Workspace, IRunningD
private readonly RunningDocumentTableEventTracker _runningDocumentTableEventTracker;
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new Dictionary<Guid, LanguageInformation>();
private readonly Dictionary<Guid, LanguageInformation> _languageInformationByLanguageGuid = new();
/// <summary>
/// <see cref="WorkspaceRegistration"/> instances for all open buffers being tracked by by this object
......
......@@ -16,7 +16,7 @@ internal sealed partial class VisualStudioRuleSetManager
private sealed class RuleSetFile : IRuleSetFile, IDisposable
{
private readonly VisualStudioRuleSetManager _ruleSetManager;
private readonly object _gate = new object();
private readonly object _gate = new();
private FileChangeWatcher.IContext _fileChangeContext;
......
......@@ -17,7 +17,7 @@ internal sealed partial class VisualStudioRuleSetManager : IWorkspaceService
private readonly IForegroundNotificationService _foregroundNotificationService;
private readonly IAsynchronousOperationListener _listener;
private readonly ReferenceCountedDisposableCache<string, RuleSetFile> _ruleSetFileMap = new ReferenceCountedDisposableCache<string, RuleSetFile>();
private readonly ReferenceCountedDisposableCache<string, RuleSetFile> _ruleSetFileMap = new();
public VisualStudioRuleSetManager(
FileChangeWatcher fileChangeWatcher, IForegroundNotificationService foregroundNotificationService, IAsynchronousOperationListener listener)
......
......@@ -22,7 +22,7 @@ internal class SolutionChangeAccumulator
/// <see cref="WorkspaceChangeKind.SolutionChanged"/> if we can't give a more precise type.
/// </summary>
private WorkspaceChangeKind? _workspaceChangeKind;
private readonly List<DocumentId> _documentIdsRemoved = new List<DocumentId>();
private readonly List<DocumentId> _documentIdsRemoved = new();
public SolutionChangeAccumulator(Solution startingSolution)
=> Solution = startingSolution;
......
......@@ -27,7 +27,7 @@ internal partial class VisualStudioAddSolutionItemService : IAddSolutionItemServ
{
private const string SolutionItemsFolderName = "Solution Items";
private readonly object _gate = new object();
private readonly object _gate = new();
private readonly IThreadingContext _threadingContext;
private readonly ConcurrentDictionary<string, FileChangeTracker> _fileChangeTrackers;
......
......@@ -28,7 +28,7 @@ internal sealed class VisualStudioAnalyzer : IDisposable
private readonly string _language;
// these 2 are mutable states that must be guarded under the _gate.
private readonly object _gate = new object();
private readonly object _gate = new();
private AnalyzerReference? _analyzerReference;
private ImmutableArray<DiagnosticData> _analyzerLoadErrors = ImmutableArray<DiagnosticData>.Empty;
......
......@@ -35,7 +35,7 @@ private VisualStudioMefHostServices(ExportProvider exportProvider)
}
public static VisualStudioMefHostServices Create(ExportProvider exportProvider)
=> new VisualStudioMefHostServices(exportProvider);
=> new(exportProvider);
/// <summary>
/// Creates a new <see cref="HostWorkspaceServices"/> associated with the specified workspace.
......
......@@ -39,23 +39,23 @@ internal sealed class VisualStudioProject
/// </summary>
/// <remarks>This is, for now, intentionally pessimistic. There are no doubt ways that we could allow more to run in parallel,
/// but the current tradeoff is for simplicity of code and "obvious correctness" than something that is subtle, fast, and wrong.</remarks>
private readonly object _gate = new object();
private readonly object _gate = new();
/// <summary>
/// The number of active batch scopes. If this is zero, we are not batching, non-zero means we are batching.
/// </summary>
private int _activeBatchScopes = 0;
private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesAddedInBatch = new List<(string path, MetadataReferenceProperties properties)>();
private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesRemovedInBatch = new List<(string path, MetadataReferenceProperties properties)>();
private readonly List<ProjectReference> _projectReferencesAddedInBatch = new List<ProjectReference>();
private readonly List<ProjectReference> _projectReferencesRemovedInBatch = new List<ProjectReference>();
private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesAddedInBatch = new();
private readonly List<(string path, MetadataReferenceProperties properties)> _metadataReferencesRemovedInBatch = new();
private readonly List<ProjectReference> _projectReferencesAddedInBatch = new();
private readonly List<ProjectReference> _projectReferencesRemovedInBatch = new();
private readonly Dictionary<string, VisualStudioAnalyzer> _analyzerPathsToAnalyzers = new Dictionary<string, VisualStudioAnalyzer>();
private readonly List<VisualStudioAnalyzer> _analyzersAddedInBatch = new List<VisualStudioAnalyzer>();
private readonly List<VisualStudioAnalyzer> _analyzersRemovedInBatch = new List<VisualStudioAnalyzer>();
private readonly Dictionary<string, VisualStudioAnalyzer> _analyzerPathsToAnalyzers = new();
private readonly List<VisualStudioAnalyzer> _analyzersAddedInBatch = new();
private readonly List<VisualStudioAnalyzer> _analyzersRemovedInBatch = new();
private readonly List<Func<Solution, Solution>> _projectPropertyModificationsInBatch = new List<Func<Solution, Solution>>();
private readonly List<Func<Solution, Solution>> _projectPropertyModificationsInBatch = new();
private string _assemblyName;
private string _displayName;
......@@ -83,13 +83,13 @@ internal sealed class VisualStudioProject
// Effective boolean value to determine if analyzers should be executed based on _runAnalyzersPropertyValue and _runAnalyzersDuringLiveAnalysisPropertyValue.
private bool _runAnalyzers = true;
private readonly Dictionary<string, ImmutableArray<MetadataReferenceProperties>> _allMetadataReferences = new Dictionary<string, ImmutableArray<MetadataReferenceProperties>>();
private readonly Dictionary<string, ImmutableArray<MetadataReferenceProperties>> _allMetadataReferences = new();
/// <summary>
/// The file watching tokens for the documents in this project. We get the tokens even when we're in a batch, so the files here
/// may not be in the actual workspace yet.
/// </summary>
private readonly Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken> _documentFileWatchingTokens = new Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken>();
private readonly Dictionary<DocumentId, FileChangeWatcher.IFileWatchingToken> _documentFileWatchingTokens = new();
/// <summary>
/// A file change context used to watch source files, additional files, and analyzer config files for this project. It's automatically set to watch the user's project
......@@ -100,7 +100,7 @@ internal sealed class VisualStudioProject
/// <summary>
/// track whether we have been subscribed to <see cref="IDynamicFileInfoProvider.Updated"/> event
/// </summary>
private readonly HashSet<IDynamicFileInfoProvider> _eventSubscriptionTracker = new HashSet<IDynamicFileInfoProvider>();
private readonly HashSet<IDynamicFileInfoProvider> _eventSubscriptionTracker = new();
/// <summary>
/// Map of the original dynamic file path to the <see cref="DynamicFileInfo.FilePath"/> that was associated with it.
......@@ -114,7 +114,7 @@ internal sealed class VisualStudioProject
/// The workspace snapshot will only have a document with <see cref="DynamicFileInfo.FilePath"/> (the value) but not the
/// original dynamic file path (the key).
/// </summary>
private readonly Dictionary<string, string?> _dynamicFilePathMaps = new Dictionary<string, string?>();
private readonly Dictionary<string, string?> _dynamicFilePathMaps = new();
private readonly BatchingDocumentCollection _sourceFiles;
private readonly BatchingDocumentCollection _additionalFiles;
......@@ -1141,7 +1141,7 @@ private sealed class BatchingDocumentCollection
/// The map of file paths to the underlying <see cref="DocumentId"/>. This document may exist in <see cref="_documentsAddedInBatch"/> or has been
/// pushed to the actual workspace.
/// </summary>
private readonly Dictionary<string, DocumentId> _documentPathsToDocumentIds = new Dictionary<string, DocumentId>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DocumentId> _documentPathsToDocumentIds = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// A map of explicitly-added "always open" <see cref="SourceTextContainer"/> and their associated <see cref="DocumentId"/>. This does not contain
......@@ -1152,7 +1152,7 @@ private sealed class BatchingDocumentCollection
/// <summary>
/// The map of <see cref="DocumentId"/> to <see cref="IDynamicFileInfoProvider"/> whose <see cref="DynamicFileInfo"/> got added into <see cref="Workspace"/>
/// </summary>
private readonly Dictionary<DocumentId, IDynamicFileInfoProvider> _documentIdToDynamicFileInfoProvider = new Dictionary<DocumentId, IDynamicFileInfoProvider>();
private readonly Dictionary<DocumentId, IDynamicFileInfoProvider> _documentIdToDynamicFileInfoProvider = new();
/// <summary>
/// The current list of documents that are to be added in this batch.
......@@ -1162,7 +1162,7 @@ private sealed class BatchingDocumentCollection
/// <summary>
/// The current list of documents that are being removed in this batch. Once the document is in this list, it is no longer in <see cref="_documentPathsToDocumentIds"/>.
/// </summary>
private readonly List<DocumentId> _documentsRemovedInBatch = new List<DocumentId>();
private readonly List<DocumentId> _documentsRemovedInBatch = new();
/// <summary>
/// The current list of document file paths that will be ordered in a batch.
......
......@@ -26,7 +26,7 @@ internal class VisualStudioProjectOptionsProcessor : IDisposable
/// Gate to guard all mutable fields in this class.
/// The lock hierarchy means you are allowed to call out of this class and into <see cref="_project"/> while holding the lock.
/// </summary>
private readonly object _gate = new object();
private readonly object _gate = new();
/// <summary>
/// A hashed checksum of the last command line we were set to. We use this
......
......@@ -24,7 +24,7 @@ internal sealed partial class VisualStudioProjectTracker
internal HostWorkspaceServices WorkspaceServices => _workspace.Services;
[Obsolete("This is a compatibility shim for TypeScript; please do not use it.")]
private readonly Dictionary<ProjectId, AbstractProject> _projects = new Dictionary<ProjectId, AbstractProject>();
private readonly Dictionary<ProjectId, AbstractProject> _projects = new();
[Obsolete("This is a compatibility shim; please do not use it.")]
public VisualStudioProjectTracker(Workspace workspace, VisualStudioProjectFactory projectFactory, IThreadingContext threadingContext)
......
......@@ -46,7 +46,7 @@ public sealed class OpenFileTracker : IRunningDocumentTableEventListener
/// <see cref="_justEnumerateTheEntireRunningDocumentTable"/> and <see cref="_taskPending"/>. These are the only mutable fields
/// in this class that are modified from multiple threads.
/// </summary>
private readonly object _gate = new object();
private readonly object _gate = new();
private HashSet<string>? _fileNamesToCheckForOpenDocuments;
/// <summary>
......@@ -62,14 +62,14 @@ public sealed class OpenFileTracker : IRunningDocumentTableEventListener
#region Fields read/and written to only on the UI thread to track active context for files
private readonly ReferenceCountedDisposableCache<IVsHierarchy, HierarchyEventSink> _hierarchyEventSinkCache = new ReferenceCountedDisposableCache<IVsHierarchy, HierarchyEventSink>();
private readonly ReferenceCountedDisposableCache<IVsHierarchy, HierarchyEventSink> _hierarchyEventSinkCache = new();
/// <summary>
/// The IVsHierarchies we have subscribed to to watch for any changes to this moniker. We track this per moniker, so
/// when a document is closed we know what we have to incrementally unsubscribe from rather than having to unsubscribe from everything.
/// </summary>
private readonly MultiDictionary<string, IReferenceCountedDisposable<ICacheEntry<IVsHierarchy, HierarchyEventSink>>> _watchedHierarchiesForDocumentMoniker
= new MultiDictionary<string, IReferenceCountedDisposable<ICacheEntry<IVsHierarchy, HierarchyEventSink>>>();
= new();
#endregion
......
......@@ -53,7 +53,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem
/// </summary>
internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspace
{
private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1);
private static readonly IntPtr s_docDataExisting_Unknown = new(-1);
private const string AppCodeFolderName = "App_Code";
private readonly IThreadingContext _threadingContext;
......@@ -65,7 +65,7 @@ internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspac
private readonly ITextBufferCloneService _textBufferCloneService;
private readonly object _gate = new object();
private readonly object _gate = new();
/// <summary>
/// A <see cref="ForegroundThreadAffinitizedObject"/> to make assertions that stuff is on the right thread.
......@@ -74,18 +74,18 @@ internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspac
private ImmutableDictionary<ProjectId, IVsHierarchy?> _projectToHierarchyMap = ImmutableDictionary<ProjectId, IVsHierarchy?>.Empty;
private ImmutableDictionary<ProjectId, Guid> _projectToGuidMap = ImmutableDictionary<ProjectId, Guid>.Empty;
private readonly Dictionary<ProjectId, string?> _projectToMaxSupportedLangVersionMap = new Dictionary<ProjectId, string?>();
private readonly Dictionary<ProjectId, string?> _projectToMaxSupportedLangVersionMap = new();
/// <summary>
/// A map to fetch the path to a rule set file for a project. This right now is only used to implement
/// <see cref="TryGetRuleSetPathForProject(ProjectId)"/> and any other use is extremely suspicious, since direct use of this is out of
/// sync with the Workspace if there is active batching happening.
/// </summary>
private readonly Dictionary<ProjectId, Func<string?>> _projectToRuleSetFilePath = new Dictionary<ProjectId, Func<string?>>();
private readonly Dictionary<ProjectId, Func<string?>> _projectToRuleSetFilePath = new();
private readonly Dictionary<string, List<VisualStudioProject>> _projectSystemNameToProjectsMap = new Dictionary<string, List<VisualStudioProject>>();
private readonly Dictionary<string, List<VisualStudioProject>> _projectSystemNameToProjectsMap = new();
private readonly Dictionary<string, UIContext?> _languageToProjectExistsUIContext = new Dictionary<string, UIContext?>();
private readonly Dictionary<string, UIContext?> _languageToProjectExistsUIContext = new();
/// <summary>
/// A set of documents that were added by <see cref="VisualStudioProject.AddSourceTextContainer"/>, and aren't otherwise
......@@ -1559,7 +1559,7 @@ public void ApplyBatchChangeToWorkspace(Func<CodeAnalysis.Solution, SolutionChan
}
}
private readonly Dictionary<ProjectId, ProjectReferenceInformation> _projectReferenceInfoMap = new Dictionary<ProjectId, ProjectReferenceInformation>();
private readonly Dictionary<ProjectId, ProjectReferenceInformation> _projectReferenceInfoMap = new();
private ProjectReferenceInformation GetReferenceInfo_NoLock(ProjectId projectId)
{
......@@ -1616,7 +1616,7 @@ protected internal override void OnProjectRemoved(ProjectId projectId)
private sealed class ProjectReferenceInformation
{
public readonly List<string> OutputPaths = new List<string>();
public readonly List<string> OutputPaths = new();
public readonly List<(string path, ProjectReference projectReference)> ConvertedProjectReferences = new List<(string path, ProjectReference)>();
}
......@@ -1626,7 +1626,7 @@ private sealed class ProjectReferenceInformation
/// any bug by a project adding the wrong output path means we could end up with some duplication.
/// In that case, we'll temporarily have two until (hopefully) somebody removes it.
/// </summary>
private readonly Dictionary<string, List<ProjectId>> _projectsByOutputPath = new Dictionary<string, List<ProjectId>>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, List<ProjectId>> _projectsByOutputPath = new(StringComparer.OrdinalIgnoreCase);
public void AddProjectOutputPath(ProjectId projectId, string outputPath)
{
......
......@@ -40,7 +40,7 @@ internal abstract class AbstractSnippetInfoService : ForegroundThreadAffinitized
// Guard the snippets and snippetShortcut fields so that returned result sets are always
// complete.
protected object cacheGuard = new object();
protected object cacheGuard = new();
private readonly IAsynchronousOperationListener _waiter;
private readonly IThreadingContext _threadingContext;
......
......@@ -14,7 +14,7 @@ public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl
=> CreateEventProcessor();
protected virtual EventProcessor CreateEventProcessor()
=> new EventProcessor();
=> new();
protected class EventProcessor : TableControlEventProcessorBase
{
......
......@@ -44,7 +44,7 @@ public override ProjectId ProjectId
=> Data.ProjectId;
public override LinePosition GetOriginalPosition()
=> new LinePosition(Data.DataLocation?.OriginalStartLine ?? 0, Data.DataLocation?.OriginalStartColumn ?? 0);
=> new(Data.DataLocation?.OriginalStartLine ?? 0, Data.DataLocation?.OriginalStartColumn ?? 0);
public override string GetOriginalFilePath()
=> Data.DataLocation?.OriginalFilePath;
......@@ -78,7 +78,7 @@ public override bool EqualsIgnoringLocation(TableItem other)
/// </summary>
internal sealed class GroupingComparer : IEqualityComparer<DiagnosticData>, IEqualityComparer<DiagnosticTableItem>
{
public static readonly GroupingComparer Instance = new GroupingComparer();
public static readonly GroupingComparer Instance = new();
public bool Equals(DiagnosticData left, DiagnosticData right)
{
......
......@@ -12,9 +12,9 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
internal class OpenDocumentTracker<TItem>
where TItem : TableItem
{
private readonly object _gate = new object();
private readonly object _gate = new();
private readonly Dictionary<DocumentId, Dictionary<object, WeakReference<AbstractTableEntriesSnapshot<TItem>>>> _map =
new Dictionary<DocumentId, Dictionary<object, WeakReference<AbstractTableEntriesSnapshot<TItem>>>>();
new();
private readonly Workspace _workspace;
......
......@@ -15,11 +15,11 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
internal class TableEntriesFactory<TItem, TData> : ITableEntriesSnapshotFactory
where TItem : TableItem
{
private readonly object _gate = new object();
private readonly object _gate = new();
private readonly AbstractTableDataSource<TItem, TData> _tableSource;
private readonly AggregatedEntriesSource _entriesSources;
private readonly WeakReference<ITableEntriesSnapshot> _lastSnapshotWeakReference = new WeakReference<ITableEntriesSnapshot>(null);
private readonly WeakReference<ITableEntriesSnapshot> _lastSnapshotWeakReference = new(null);
private int _lastVersion = 0;
......
......@@ -44,7 +44,7 @@ public override ProjectId ProjectId
=> Data.DocumentId.ProjectId;
public override LinePosition GetOriginalPosition()
=> new LinePosition(Data.OriginalLine, Data.OriginalColumn);
=> new(Data.OriginalLine, Data.OriginalColumn);
public override string GetOriginalFilePath()
=> Data.OriginalFilePath;
......@@ -68,7 +68,7 @@ public override bool EqualsIgnoringLocation(TableItem other)
/// </summary>
internal sealed class GroupingComparer : IEqualityComparer<TodoCommentData>, IEqualityComparer<TodoTableItem>
{
public static readonly GroupingComparer Instance = new GroupingComparer();
public static readonly GroupingComparer Instance = new();
public bool Equals(TodoCommentData left, TodoCommentData right)
{
......
......@@ -22,13 +22,13 @@ internal static class ValueTypeCache
private class Cache<T> where T : struct
{
public static readonly Cache<T> Instance = new Cache<T>();
public static readonly Cache<T> Instance = new();
private static readonly Func<T, object> s_boxer = v => (object)v;
// this will be never released, must be used only for fixed size set
private readonly ConcurrentDictionary<T, object> _map =
new ConcurrentDictionary<T, object>(concurrencyLevel: 2, capacity: 5);
new(concurrencyLevel: 2, capacity: 5);
public object GetOrCreate(T value)
=> _map.GetOrAdd(value, s_boxer);
......
......@@ -27,7 +27,7 @@ internal partial class VisualStudioDiagnosticListTable : VisualStudioBaseDiagnos
/// </summary>
private class BuildTableDataSource : AbstractTableDataSource<DiagnosticTableItem, object>
{
private readonly object _key = new object();
private readonly object _key = new();
private readonly ExternalErrorDiagnosticUpdateSource _buildErrorSource;
......
......@@ -53,7 +53,7 @@ internal sealed class ExternalErrorDiagnosticUpdateSource : IDiagnosticUpdateSou
private readonly TaskQueue _taskQueue;
// Gate for concurrent access and fields guarded with this gate.
private readonly object _gate = new object();
private readonly object _gate = new();
private InProgressState? _stateDoNotAccessDirectly;
private CancellationTokenSource? _activeCancellationSourceDoNotAccessDirectly;
......@@ -506,7 +506,7 @@ private void RaiseDiagnosticsRemoved(object? id, Solution solution, ProjectId? p
CreateArgumentKey(id), _workspace, solution, projectId, documentId));
}
private static ArgumentKey CreateArgumentKey(object? id) => new ArgumentKey(id);
private static ArgumentKey CreateArgumentKey(object? id) => new(id);
private void RaiseBuildProgressChanged(BuildProgress progress)
=> BuildProgressChanged?.Invoke(this, progress);
......@@ -538,7 +538,7 @@ private sealed class InProgressState
/// <remarks>
/// This map may be accessed concurrently, so needs to ensure thread safety by using locks.
/// </remarks>
private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _allDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>();
private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _allDiagnosticIdMap = new();
/// <summary>
/// Map from project ID to all the possible intellisense analyzer diagnostic IDs that can be reported in the project.
......@@ -549,7 +549,7 @@ private sealed class InProgressState
/// <remarks>
/// This map may be accessed concurrently, so needs to ensure thread safety by using locks.
/// </remarks>
private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _liveDiagnosticIdMap = new Dictionary<ProjectId, ImmutableHashSet<string>>();
private readonly Dictionary<ProjectId, ImmutableHashSet<string>> _liveDiagnosticIdMap = new();
// Fields that are used only from APIs invoked from serialized task queue, hence don't need to be thread safe.
#region Serialized fields
......@@ -560,7 +560,7 @@ private sealed class InProgressState
/// Integral counter value for each diagnostic is used to order the reported diagnostics in error list
/// based on the order in which they were reported during build.
/// </summary>
private readonly Dictionary<ProjectId, Dictionary<DiagnosticData, int>> _projectMap = new Dictionary<ProjectId, Dictionary<DiagnosticData, int>>();
private readonly Dictionary<ProjectId, Dictionary<DiagnosticData, int>> _projectMap = new();
/// <summary>
/// Map from document ID to a dictionary of reported document level diagnostics to an integral counter.
......@@ -568,23 +568,23 @@ private sealed class InProgressState
/// Integral counter value for each diagnostic is used to order the reported diagnostics in error list
/// based on the order in which they were reported during build.
/// </summary>
private readonly Dictionary<DocumentId, Dictionary<DiagnosticData, int>> _documentMap = new Dictionary<DocumentId, Dictionary<DiagnosticData, int>>();
private readonly Dictionary<DocumentId, Dictionary<DiagnosticData, int>> _documentMap = new();
/// <summary>
/// Set of projects for which we have already cleared the build and intellisense diagnostics in the error list.
/// </summary>
private readonly HashSet<ProjectId> _projectsWithErrorsCleared = new HashSet<ProjectId>();
private readonly HashSet<ProjectId> _projectsWithErrorsCleared = new();
/// <summary>
/// Set of projects for which we have reported all intellisense/live diagnostics.
/// </summary>
private readonly HashSet<ProjectId> _projectsWithAllLiveErrorsReported = new HashSet<ProjectId>();
private readonly HashSet<ProjectId> _projectsWithAllLiveErrorsReported = new();
/// <summary>
/// Set of projects which have at least one project or document diagnostic in
/// <see cref="_projectMap"/> and/or <see cref="_documentMap"/>.
/// </summary>
private readonly HashSet<ProjectId> _projectsWithErrors = new HashSet<ProjectId>();
private readonly HashSet<ProjectId> _projectsWithErrors = new();
/// <summary>
/// Last project for which build reported an error through one of the <see cref="M:AddError"/> methods.
......@@ -909,7 +909,7 @@ public override int GetHashCode()
private sealed class DiagnosticDataComparer : IEqualityComparer<DiagnosticData>
{
public static readonly DiagnosticDataComparer Instance = new DiagnosticDataComparer();
public static readonly DiagnosticDataComparer Instance = new();
public bool Equals(DiagnosticData item1, DiagnosticData item2)
{
......
......@@ -21,8 +21,8 @@ internal sealed class HostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateS
{
private readonly Lazy<VisualStudioWorkspaceImpl> _workspace;
private readonly object _gate = new object();
private readonly Dictionary<ProjectId, HashSet<object>> _diagnosticMap = new Dictionary<ProjectId, HashSet<object>>();
private readonly object _gate = new();
private readonly Dictionary<ProjectId, HashSet<object>> _diagnosticMap = new();
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
......
......@@ -43,7 +43,7 @@ internal class VisualStudioTodoCommentsService
private readonly EventListenerTracker<ITodoListProvider> _eventListenerTracker;
private readonly ConcurrentDictionary<DocumentId, ImmutableArray<TodoCommentData>> _documentToInfos
= new ConcurrentDictionary<DocumentId, ImmutableArray<TodoCommentData>>();
= new();
/// <summary>
/// Remote service connection. Created on demand when we startup and then
......@@ -55,7 +55,7 @@ internal class VisualStudioTodoCommentsService
/// Queue where we enqueue the information we get from OOP to process in batch in the future.
/// </summary>
private readonly TaskCompletionSource<AsyncBatchingWorkQueue<DocumentAndComments>> _workQueueSource
= new TaskCompletionSource<AsyncBatchingWorkQueue<DocumentAndComments>>();
= new();
public event EventHandler<TodoItemsUpdatedArgs>? TodoListUpdated;
......
......@@ -15,13 +15,13 @@ internal class SymbolViewModel<T> : AbstractNotifyPropertyChanged where T : ISym
public T Symbol { get; }
private static readonly SymbolDisplayFormat s_symbolDisplayFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_symbolDisplayFormat = new(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeOptionalBrackets,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
private static readonly SymbolDisplayFormat s_symbolAutomationFormat = new SymbolDisplayFormat(
private static readonly SymbolDisplayFormat s_symbolAutomationFormat = new(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeOptionalBrackets,
......
......@@ -293,7 +293,7 @@ private static (SourceText, TextSpan) GetContentAndMappedSpan(ExcerptMode mode,
}
private static TextSpan GetSpanOnContent(TextSpan targetSpan, TextSpan excerptSpan)
=> new TextSpan(targetSpan.Start - excerptSpan.Start, targetSpan.Length);
=> new(targetSpan.Start - excerptSpan.Start, targetSpan.Length);
}
}
}
......
......@@ -55,13 +55,13 @@ internal sealed partial class ContainedDocument : ForegroundThreadAffinitizedObj
private const string FunctionsRazor = "functions";
private const string CodeRazor = "code";
private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions
private static readonly EditOptions s_venusEditOptions = new(new StringDifferenceOptions
{
DifferenceType = StringDifferenceTypes.Character,
IgnoreTrimWhiteSpace = false
});
private static readonly ConcurrentDictionary<DocumentId, ContainedDocument> s_containedDocuments = new ConcurrentDictionary<DocumentId, ContainedDocument>();
private static readonly ConcurrentDictionary<DocumentId, ContainedDocument> s_containedDocuments = new();
public static ContainedDocument TryGetContainedDocument(DocumentId id)
{
......
......@@ -21,7 +21,7 @@ internal static class WatsonReporter
{
private static Dictionary<string, string>? s_capturedFileContent;
private static readonly object _guard = new object();
private static readonly object _guard = new();
private static ImmutableArray<TelemetrySession> s_telemetrySessions = ImmutableArray<TelemetrySession>.Empty;
private static ImmutableArray<TraceSource> s_loggers = ImmutableArray<TraceSource>.Empty;
......
......@@ -54,7 +54,7 @@ internal sealed class SourceGeneratedFileManager : IRunningDocumentTableEventLis
/// <summary>
/// Map of currently open generated files; the key is the generated full file path.
/// </summary>
private readonly Dictionary<string, OpenSourceGeneratedFile> _openFiles = new Dictionary<string, OpenSourceGeneratedFile>();
private readonly Dictionary<string, OpenSourceGeneratedFile> _openFiles = new();
private readonly VisualStudioWorkspace _visualStudioWorkspace;
[ImportingConstructor]
......@@ -216,7 +216,7 @@ private class OpenSourceGeneratedFile : ForegroundThreadAffinitizedObject, IDisp
/// A cancellation token used for any background updating of this file; this is cancelled on the UI thread
/// when the file is closed.
/// </summary>
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly CancellationTokenSource _cancellationTokenSource = new();
/// <summary>
/// A queue used to batch updates to the file.
......
......@@ -35,7 +35,7 @@ public VisualStudioDocumentTrackingService(VisualStudioActiveDocumentTracker act
_workspace = workspace;
}
private readonly object _gate = new object();
private readonly object _gate = new();
private int _subscriptions = 0;
private event EventHandler<DocumentId> _activeDocumentChangedEventHandler;
......
......@@ -10,7 +10,7 @@ namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal static class VisualStudioNavigationOptions
{
public static readonly PerLanguageOption2<bool> NavigateToObjectBrowser = new PerLanguageOption2<bool>(nameof(VisualStudioNavigationOptions), nameof(NavigateToObjectBrowser), defaultValue: false,
public static readonly PerLanguageOption2<bool> NavigateToObjectBrowser = new(nameof(VisualStudioNavigationOptions), nameof(NavigateToObjectBrowser), defaultValue: false,
storageLocations: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.NavigateToObjectBrowser"));
}
}
......@@ -87,7 +87,7 @@ internal static void ConnectProjectCacheServiceToDocumentTracking(HostWorkspaceS
private class ActiveProjectCacheManager
{
private readonly ProjectCacheService _projectCacheService;
private readonly object _guard = new object();
private readonly object _guard = new();
private ProjectId _mostRecentActiveProjectId;
private IDisposable _mostRecentCache;
......
......@@ -63,7 +63,7 @@ public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
/// </summary>
private class Service : IWorkspaceStatusService
{
private readonly SemaphoreSlim _initializationGate = new SemaphoreSlim(initialCount: 1);
private readonly SemaphoreSlim _initializationGate = new(initialCount: 1);
private readonly IAsyncServiceProvider2 _serviceProvider;
private bool _initialized = false;
......
......@@ -13,7 +13,7 @@ internal partial class PackageInstallerService
{
private struct ProjectState
{
public static readonly ProjectState Disabled = new ProjectState(isEnabled: false, ImmutableDictionary<string, string>.Empty);
public static readonly ProjectState Disabled = new(isEnabled: false, ImmutableDictionary<string, string>.Empty);
public readonly bool IsEnabled;
......
......@@ -77,12 +77,12 @@ internal partial class PackageInstallerService : AbstractDelayStartedService, IP
private readonly AsyncBatchingWorkQueue<(bool solutionChanged, ProjectId? changedProject)>? _workQueue;
private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectToInstalledPackageAndVersion =
new ConcurrentDictionary<ProjectId, ProjectState>();
new();
/// <summary>
/// Lock used to protect reads and writes of <see cref="_packageSourcesTask"/>.
/// </summary>
private readonly object _gate = new object();
private readonly object _gate = new();
/// <summary>
/// Task uses to compute the set of package sources on demand when asked the first time. The value will be
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册