diff --git a/src/libraries/Common/src/System/CodeDom/CodeObject.cs b/src/libraries/Common/src/System/CodeDom/CodeObject.cs index f1cd5e40f4af2b..fa06d64db95c9b 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeObject.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeObject.cs @@ -16,10 +16,8 @@ public class CodeObject internal class CodeObject #endif { - private IDictionary? _userData; - public CodeObject() { } - public IDictionary UserData => _userData ??= new ListDictionary(); + public IDictionary UserData => field ??= new ListDictionary(); } } diff --git a/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs b/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs index 956e6ca855e2ef..9a6926208f8690 100644 --- a/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs +++ b/src/libraries/Common/src/System/Data/Common/AdapterUtil.cs @@ -19,11 +19,8 @@ internal static partial class ADP { // NOTE: Initializing a Task in SQL CLR requires the "UNSAFE" permission set (https://learn.microsoft.com/dotnet/framework/performance/sql-server-programming-and-host-protection-attributes) // Therefore we are lazily initializing these Tasks to avoid forcing customers to use the "UNSAFE" set when they are actually using no Async features - private static Task? _trueTask; - internal static Task TrueTask => _trueTask ??= Task.FromResult(true); - - private static Task? _falseTask; - internal static Task FalseTask => _falseTask ??= Task.FromResult(false); + internal static Task TrueTask => field ??= Task.FromResult(true); + internal static Task FalseTask => field ??= Task.FromResult(false); internal const CompareOptions DefaultCompareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase; internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout; diff --git a/src/libraries/Common/src/System/Security/Cryptography/Oids.Shared.cs b/src/libraries/Common/src/System/Security/Cryptography/Oids.Shared.cs index 2f584a0bbfd7f8..8ff904d32edfe3 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Oids.Shared.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/Oids.Shared.cs @@ -8,74 +8,41 @@ namespace System.Security.Cryptography { internal static partial class Oids { - private static Oid? s_rsaOid; - private static Oid? s_ecPublicKeyOid; - private static Oid? s_tripleDesCbcOid; - private static Oid? s_aes256CbcOid; - private static Oid? s_secp256R1Oid; - private static Oid? s_secp384R1Oid; - private static Oid? s_secp521R1Oid; - private static Oid? s_sha256Oid; - private static Oid? s_pkcs7DataOid; - private static Oid? s_contentTypeOid; - private static Oid? s_documentDescriptionOid; - private static Oid? s_documentNameOid; - private static Oid? s_localKeyIdOid; - private static Oid? s_messageDigestOid; - private static Oid? s_signingTimeOid; - private static Oid? s_pkcs9ExtensionRequestOid; - private static Oid? s_basicConstraints2Oid; - private static Oid? s_enhancedKeyUsageOid; - private static Oid? s_keyUsageOid; - private static Oid? s_subjectAltNameOid; - private static Oid? s_subjectKeyIdentifierOid; - private static Oid? s_authorityKeyIdentifierOid; - private static Oid? s_authorityInformationAccessOid; - private static Oid? s_crlNumberOid; - private static Oid? s_crlDistributionPointOid; - private static Oid? s_commonNameOid; - private static Oid? s_countryOrRegionOid; - private static Oid? s_localityNameOid; - private static Oid? s_stateOrProvinceNameOid; - private static Oid? s_organizationOid; - private static Oid? s_organizationalUnitOid; - private static Oid? s_emailAddressOid; - - internal static Oid RsaOid => s_rsaOid ??= InitializeOid(Rsa); - internal static Oid EcPublicKeyOid => s_ecPublicKeyOid ??= InitializeOid(EcPublicKey); - internal static Oid TripleDesCbcOid => s_tripleDesCbcOid ??= InitializeOid(TripleDesCbc); - internal static Oid Aes256CbcOid => s_aes256CbcOid ??= InitializeOid(Aes256Cbc); - internal static Oid secp256r1Oid => s_secp256R1Oid ??= new Oid(secp256r1, nameof(ECCurve.NamedCurves.nistP256)); - internal static Oid secp384r1Oid => s_secp384R1Oid ??= new Oid(secp384r1, nameof(ECCurve.NamedCurves.nistP384)); - internal static Oid secp521r1Oid => s_secp521R1Oid ??= new Oid(secp521r1, nameof(ECCurve.NamedCurves.nistP521)); - internal static Oid Sha256Oid => s_sha256Oid ??= InitializeOid(Sha256); - - internal static Oid Pkcs7DataOid => s_pkcs7DataOid ??= InitializeOid(Pkcs7Data); - internal static Oid ContentTypeOid => s_contentTypeOid ??= InitializeOid(ContentType); - internal static Oid DocumentDescriptionOid => s_documentDescriptionOid ??= InitializeOid(DocumentDescription); - internal static Oid DocumentNameOid => s_documentNameOid ??= InitializeOid(DocumentName); - internal static Oid LocalKeyIdOid => s_localKeyIdOid ??= InitializeOid(LocalKeyId); - internal static Oid MessageDigestOid => s_messageDigestOid ??= InitializeOid(MessageDigest); - internal static Oid SigningTimeOid => s_signingTimeOid ??= InitializeOid(SigningTime); - internal static Oid Pkcs9ExtensionRequestOid => s_pkcs9ExtensionRequestOid ??= InitializeOid(Pkcs9ExtensionRequest); - - internal static Oid BasicConstraints2Oid => s_basicConstraints2Oid ??= InitializeOid(BasicConstraints2); - internal static Oid EnhancedKeyUsageOid => s_enhancedKeyUsageOid ??= InitializeOid(EnhancedKeyUsage); - internal static Oid KeyUsageOid => s_keyUsageOid ??= InitializeOid(KeyUsage); - internal static Oid AuthorityKeyIdentifierOid => s_authorityKeyIdentifierOid ??= InitializeOid(AuthorityKeyIdentifier); - internal static Oid SubjectKeyIdentifierOid => s_subjectKeyIdentifierOid ??= InitializeOid(SubjectKeyIdentifier); - internal static Oid SubjectAltNameOid => s_subjectAltNameOid ??= InitializeOid(SubjectAltName); - internal static Oid AuthorityInformationAccessOid => s_authorityInformationAccessOid ??= InitializeOid(AuthorityInformationAccess); - internal static Oid CrlNumberOid => s_crlNumberOid ??= InitializeOid(CrlNumber); - internal static Oid CrlDistributionPointsOid => s_crlDistributionPointOid ??= InitializeOid(CrlDistributionPoints); - - internal static Oid CommonNameOid => s_commonNameOid ??= InitializeOid(CommonName); - internal static Oid CountryOrRegionNameOid => s_countryOrRegionOid ??= InitializeOid(CountryOrRegionName); - internal static Oid LocalityNameOid => s_localityNameOid ??= InitializeOid(LocalityName); - internal static Oid StateOrProvinceNameOid => s_stateOrProvinceNameOid ??= InitializeOid(StateOrProvinceName); - internal static Oid OrganizationOid => s_organizationOid ??= InitializeOid(Organization); - internal static Oid OrganizationalUnitOid => s_organizationalUnitOid ??= InitializeOid(OrganizationalUnit); - internal static Oid EmailAddressOid => s_emailAddressOid ??= InitializeOid(EmailAddress); + internal static Oid RsaOid => field ??= InitializeOid(Rsa); + internal static Oid EcPublicKeyOid => field ??= InitializeOid(EcPublicKey); + internal static Oid TripleDesCbcOid => field ??= InitializeOid(TripleDesCbc); + internal static Oid Aes256CbcOid => field ??= InitializeOid(Aes256Cbc); + internal static Oid secp256r1Oid => field ??= new Oid(secp256r1, nameof(ECCurve.NamedCurves.nistP256)); + internal static Oid secp384r1Oid => field ??= new Oid(secp384r1, nameof(ECCurve.NamedCurves.nistP384)); + internal static Oid secp521r1Oid => field ??= new Oid(secp521r1, nameof(ECCurve.NamedCurves.nistP521)); + internal static Oid Sha256Oid => field ??= InitializeOid(Sha256); + + internal static Oid Pkcs7DataOid => field ??= InitializeOid(Pkcs7Data); + internal static Oid ContentTypeOid => field ??= InitializeOid(ContentType); + internal static Oid DocumentDescriptionOid => field ??= InitializeOid(DocumentDescription); + internal static Oid DocumentNameOid => field ??= InitializeOid(DocumentName); + internal static Oid LocalKeyIdOid => field ??= InitializeOid(LocalKeyId); + internal static Oid MessageDigestOid => field ??= InitializeOid(MessageDigest); + internal static Oid SigningTimeOid => field ??= InitializeOid(SigningTime); + internal static Oid Pkcs9ExtensionRequestOid => field ??= InitializeOid(Pkcs9ExtensionRequest); + + internal static Oid BasicConstraints2Oid => field ??= InitializeOid(BasicConstraints2); + internal static Oid EnhancedKeyUsageOid => field ??= InitializeOid(EnhancedKeyUsage); + internal static Oid KeyUsageOid => field ??= InitializeOid(KeyUsage); + internal static Oid AuthorityKeyIdentifierOid => field ??= InitializeOid(AuthorityKeyIdentifier); + internal static Oid SubjectKeyIdentifierOid => field ??= InitializeOid(SubjectKeyIdentifier); + internal static Oid SubjectAltNameOid => field ??= InitializeOid(SubjectAltName); + internal static Oid AuthorityInformationAccessOid => field ??= InitializeOid(AuthorityInformationAccess); + internal static Oid CrlNumberOid => field ??= InitializeOid(CrlNumber); + internal static Oid CrlDistributionPointsOid => field ??= InitializeOid(CrlDistributionPoints); + + internal static Oid CommonNameOid => field ??= InitializeOid(CommonName); + internal static Oid CountryOrRegionNameOid => field ??= InitializeOid(CountryOrRegionName); + internal static Oid LocalityNameOid => field ??= InitializeOid(LocalityName); + internal static Oid StateOrProvinceNameOid => field ??= InitializeOid(StateOrProvinceName); + internal static Oid OrganizationOid => field ??= InitializeOid(Organization); + internal static Oid OrganizationalUnitOid => field ??= InitializeOid(OrganizationalUnit); + internal static Oid EmailAddressOid => field ??= InitializeOid(EmailAddress); private static Oid InitializeOid(string oidValue) { diff --git a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs index a40bbce709b054..f8b51f129837fb 100644 --- a/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs +++ b/src/libraries/Common/tests/TestUtilities/System/IO/FileCleanupTestBase.cs @@ -100,8 +100,7 @@ protected virtual void Dispose(bool disposing) protected string GetRandomLinkPath([CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) => Path.Combine(TestDirectoryActualCasing, GetRandomLinkName(memberName, lineNumber)); protected string GetRandomDirPath([CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) => Path.Combine(TestDirectoryActualCasing, GetRandomDirName(memberName, lineNumber)); - private string _testDirectoryActualCasing; - private string TestDirectoryActualCasing => _testDirectoryActualCasing ??= GetTestDirectoryActualCasing(); + private string TestDirectoryActualCasing => field ??= GetTestDirectoryActualCasing(); /// Gets a test file full path that is associated with the call site. /// An optional index value to use as a suffix on the file name. Typically a loop index. diff --git a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs index f9466f30103fd0..9517cea528a5fa 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpMessageHandlerBuilder.cs @@ -13,7 +13,6 @@ namespace Microsoft.Extensions.Http { internal sealed class DefaultHttpMessageHandlerBuilder : HttpMessageHandlerBuilder { - private HttpMessageHandler? _primaryHandler; private string? _name; public DefaultHttpMessageHandlerBuilder(IServiceProvider services) @@ -34,8 +33,8 @@ public override string? Name public override HttpMessageHandler PrimaryHandler { - get => _primaryHandler ??= CreatePrimaryHandler(); - set => _primaryHandler = value; + get => field ??= CreatePrimaryHandler(); + set => field = value; } public override IList AdditionalHandlers { get; } = new List(); diff --git a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs index 845725f0994af3..b493d853238385 100644 --- a/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs +++ b/src/libraries/Microsoft.Extensions.Http/src/Logging/LoggingHttpMessageHandlerBuilderFilter.cs @@ -15,8 +15,7 @@ internal sealed class LoggingHttpMessageHandlerBuilderFilter : IHttpMessageHandl { // we want to prevent a circular depencency between ILoggerFactory and IHttpMessageHandlerBuilderFilter, in case // any of ILoggerProvider instances use IHttpClientFactory to send logs to an external server - private ILoggerFactory? _loggerFactory; - private ILoggerFactory LoggerFactory => _loggerFactory ??= _serviceProvider.GetRequiredService(); + private ILoggerFactory LoggerFactory => field ??= _serviceProvider.GetRequiredService(); private readonly IServiceProvider _serviceProvider; private readonly IOptionsMonitor _optionsMonitor; diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogSettings.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogSettings.cs index 35be4111fbd586..c361d41d6ec64b 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogSettings.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogSettings.cs @@ -10,8 +10,6 @@ namespace Microsoft.Extensions.Logging.EventLog /// public class EventLogSettings { - private IEventLog? _eventLog; - /// /// Gets or sets the name of the event log. If or not specified, "Application" is the default. /// @@ -34,10 +32,10 @@ public class EventLogSettings internal IEventLog EventLog { - get => _eventLog ??= CreateDefaultEventLog(); + get => field ??= CreateDefaultEventLog(); // For unit testing purposes only. - set => _eventLog = value; + set => field = value; } private WindowsEventLog CreateDefaultEventLog() diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeArrayIndexerExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeArrayIndexerExpression.cs index 08ecec7e46da5d..70c3e1271cc5cd 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeArrayIndexerExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeArrayIndexerExpression.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeArrayIndexerExpression : CodeExpression { - private CodeExpressionCollection _indices; - public CodeArrayIndexerExpression() { } public CodeArrayIndexerExpression(CodeExpression targetObject, params CodeExpression[] indices) @@ -17,6 +15,6 @@ public CodeArrayIndexerExpression(CodeExpression targetObject, params CodeExpres public CodeExpression TargetObject { get; set; } - public CodeExpressionCollection Indices => _indices ??= new CodeExpressionCollection(); + public CodeExpressionCollection Indices => field ??= new CodeExpressionCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCastExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCastExpression.cs index c72b590ee6796c..afc31b626235b1 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCastExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCastExpression.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeCastExpression : CodeExpression { - private CodeTypeReference _targetType; - public CodeCastExpression() { } public CodeCastExpression(CodeTypeReference targetType, CodeExpression expression) @@ -29,8 +27,8 @@ public CodeCastExpression(Type targetType, CodeExpression expression) public CodeTypeReference TargetType { - get => _targetType ??= new CodeTypeReference(""); - set => _targetType = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public CodeExpression Expression { get; set; } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClause.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClause.cs index c3e95043c23119..c5e86c5b9de456 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClause.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCatchClause.cs @@ -5,7 +5,6 @@ namespace System.CodeDom { public class CodeCatchClause { - private CodeStatementCollection _statements; private CodeTypeReference _catchExceptionType; private string _localName; @@ -41,6 +40,6 @@ public CodeTypeReference CatchExceptionType set => _catchExceptionType = value; } - public CodeStatementCollection Statements => _statements ??= new CodeStatementCollection(); + public CodeStatementCollection Statements => field ??= new CodeStatementCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCompileUnit.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCompileUnit.cs index dc46a7bd3e9026..b446b1f15d60b6 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeCompileUnit.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeCompileUnit.cs @@ -7,22 +7,16 @@ namespace System.CodeDom { public class CodeCompileUnit : CodeObject { - private StringCollection _assemblies; - private CodeAttributeDeclarationCollection _attributes; - - private CodeDirectiveCollection _startDirectives; - private CodeDirectiveCollection _endDirectives; - public CodeCompileUnit() { } public CodeNamespaceCollection Namespaces { get; } = new CodeNamespaceCollection(); - public StringCollection ReferencedAssemblies => _assemblies ??= new StringCollection(); + public StringCollection ReferencedAssemblies => field ??= new StringCollection(); - public CodeAttributeDeclarationCollection AssemblyCustomAttributes => _attributes ??= new CodeAttributeDeclarationCollection(); + public CodeAttributeDeclarationCollection AssemblyCustomAttributes => field ??= new CodeAttributeDeclarationCollection(); - public CodeDirectiveCollection StartDirectives => _startDirectives ??= new CodeDirectiveCollection(); + public CodeDirectiveCollection StartDirectives => field ??= new CodeDirectiveCollection(); - public CodeDirectiveCollection EndDirectives => _endDirectives ??= new CodeDirectiveCollection(); + public CodeDirectiveCollection EndDirectives => field ??= new CodeDirectiveCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeIndexerExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeIndexerExpression.cs index 53d22aaccc1f6d..4ecc67eda5db21 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeIndexerExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeIndexerExpression.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeIndexerExpression : CodeExpression { - private CodeExpressionCollection _indices; - public CodeIndexerExpression() { } public CodeIndexerExpression(CodeExpression targetObject, params CodeExpression[] indices) @@ -17,6 +15,6 @@ public CodeIndexerExpression(CodeExpression targetObject, params CodeExpression[ public CodeExpression TargetObject { get; set; } - public CodeExpressionCollection Indices => _indices ??= new CodeExpressionCollection(); + public CodeExpressionCollection Indices => field ??= new CodeExpressionCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberEvent.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberEvent.cs index eca336ed49f44d..54587273e728e6 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberEvent.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberEvent.cs @@ -5,19 +5,16 @@ namespace System.CodeDom { public class CodeMemberEvent : CodeTypeMember { - private CodeTypeReference _type; - private CodeTypeReferenceCollection _implementationTypes; - public CodeMemberEvent() { } public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public CodeTypeReference PrivateImplementationType { get; set; } - public CodeTypeReferenceCollection ImplementationTypes => _implementationTypes ??= new CodeTypeReferenceCollection(); + public CodeTypeReferenceCollection ImplementationTypes => field ??= new CodeTypeReferenceCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberField.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberField.cs index a2b814d59b1a65..56fd7389592d83 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberField.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberField.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeMemberField : CodeTypeMember { - private CodeTypeReference _type; - public CodeMemberField() { } public CodeMemberField(CodeTypeReference type, string name) @@ -29,8 +27,8 @@ public CodeMemberField(Type type, string name) public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public CodeExpression InitExpression { get; set; } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs index e1cd920c4bc960..aae0227ed897af 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberMethod.cs @@ -7,10 +7,7 @@ public class CodeMemberMethod : CodeTypeMember { private readonly CodeParameterDeclarationExpressionCollection _parameters = new CodeParameterDeclarationExpressionCollection(); private readonly CodeStatementCollection _statements = new CodeStatementCollection(); - private CodeTypeReference _returnType; private CodeTypeReferenceCollection _implementationTypes; - private CodeAttributeDeclarationCollection _returnAttributes; - private CodeTypeParameterCollection _typeParameters; private int _populated; private const int ParametersCollection = 0x1; @@ -23,8 +20,8 @@ public class CodeMemberMethod : CodeTypeMember public CodeTypeReference ReturnType { - get => _returnType ??= new CodeTypeReference(typeof(void).FullName); - set => _returnType = value; + get => field ??= new CodeTypeReference(typeof(void).FullName); + set => field = value; } public CodeStatementCollection Statements @@ -73,8 +70,8 @@ public CodeTypeReferenceCollection ImplementationTypes } } - public CodeAttributeDeclarationCollection ReturnTypeCustomAttributes => _returnAttributes ??= new CodeAttributeDeclarationCollection(); + public CodeAttributeDeclarationCollection ReturnTypeCustomAttributes => field ??= new CodeAttributeDeclarationCollection(); - public CodeTypeParameterCollection TypeParameters => _typeParameters ??= new CodeTypeParameterCollection(); + public CodeTypeParameterCollection TypeParameters => field ??= new CodeTypeParameterCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberProperty.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberProperty.cs index 55ec1d37ec7468..f38504f313cc88 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberProperty.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeMemberProperty.cs @@ -5,19 +5,17 @@ namespace System.CodeDom { public class CodeMemberProperty : CodeTypeMember { - private CodeTypeReference _type; private bool _hasGet; private bool _hasSet; - private CodeTypeReferenceCollection _implementationTypes; public CodeTypeReference PrivateImplementationType { get; set; } - public CodeTypeReferenceCollection ImplementationTypes => _implementationTypes ??= new CodeTypeReferenceCollection(); + public CodeTypeReferenceCollection ImplementationTypes => field ??= new CodeTypeReferenceCollection(); public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public bool HasGet diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeObjectCreateExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeObjectCreateExpression.cs index f6710d3e3edc9c..0f5afd299199b3 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeObjectCreateExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeObjectCreateExpression.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeObjectCreateExpression : CodeExpression { - private CodeTypeReference _createType; - public CodeObjectCreateExpression() { } public CodeObjectCreateExpression(CodeTypeReference createType, params CodeExpression[] parameters) @@ -29,8 +27,8 @@ public CodeObjectCreateExpression(Type createType, params CodeExpression[] param public CodeTypeReference CreateType { - get => _createType ??= new CodeTypeReference(""); - set => _createType = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public CodeExpressionCollection Parameters { get; } = new CodeExpressionCollection(); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpression.cs index 60dbb1b1fb75ff..fb0420cb395681 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeParameterDeclarationExpression.cs @@ -5,10 +5,6 @@ namespace System.CodeDom { public class CodeParameterDeclarationExpression : CodeExpression { - private CodeTypeReference _type; - private string _name; - private CodeAttributeDeclarationCollection _customAttributes; - public CodeParameterDeclarationExpression() { } public CodeParameterDeclarationExpression(CodeTypeReference type, string name) @@ -31,22 +27,22 @@ public CodeParameterDeclarationExpression(Type type, string name) public CodeAttributeDeclarationCollection CustomAttributes { - get => _customAttributes ??= new CodeAttributeDeclarationCollection(); - set => _customAttributes = value; + get => field ??= new CodeAttributeDeclarationCollection(); + set => field = value; } public FieldDirection Direction { get; set; } = FieldDirection.In; public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public string Name { - get => _name ?? string.Empty; - set => _name = value; + get => field ?? string.Empty; + set => field = value; } } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatement.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatement.cs index 731d87c547fbf0..4895eb878090c3 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatement.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeStatement.cs @@ -5,13 +5,10 @@ namespace System.CodeDom { public class CodeStatement : CodeObject { - private CodeDirectiveCollection _startDirectives; - private CodeDirectiveCollection _endDirectives; - public CodeLinePragma LinePragma { get; set; } - public CodeDirectiveCollection StartDirectives => _startDirectives ??= new CodeDirectiveCollection(); + public CodeDirectiveCollection StartDirectives => field ??= new CodeDirectiveCollection(); - public CodeDirectiveCollection EndDirectives => _endDirectives ??= new CodeDirectiveCollection(); + public CodeDirectiveCollection EndDirectives => field ??= new CodeDirectiveCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclaration.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclaration.cs index bb59afa6306aae..a8b24366ed4b64 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclaration.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDeclaration.cs @@ -14,7 +14,6 @@ public class CodeTypeDeclaration : CodeTypeMember private int _populated; private const int BaseTypesCollection = 0x1; private const int MembersCollection = 0x2; - private CodeTypeParameterCollection _typeParameters; public event EventHandler PopulateBaseTypes; public event EventHandler PopulateMembers; @@ -122,6 +121,6 @@ public CodeTypeMemberCollection Members } } - public CodeTypeParameterCollection TypeParameters => _typeParameters ??= new CodeTypeParameterCollection(); + public CodeTypeParameterCollection TypeParameters => field ??= new CodeTypeParameterCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDelegate.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDelegate.cs index 4239cdf7ba208d..ab828b0f9c2583 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDelegate.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeDelegate.cs @@ -7,8 +7,6 @@ namespace System.CodeDom { public class CodeTypeDelegate : CodeTypeDeclaration { - private CodeTypeReference _returnType; - public CodeTypeDelegate() { TypeAttributes &= ~TypeAttributes.ClassSemanticsMask; @@ -24,8 +22,8 @@ public CodeTypeDelegate(string name) : this() public CodeTypeReference ReturnType { - get => _returnType ??= new CodeTypeReference(""); - set => _returnType = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } public CodeParameterDeclarationExpressionCollection Parameters { get; } = new CodeParameterDeclarationExpressionCollection(); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMember.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMember.cs index 18a8a44e822cd0..79f65b6d0fdab3 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMember.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeMember.cs @@ -5,31 +5,26 @@ namespace System.CodeDom { public class CodeTypeMember : CodeObject { - private string _name; - private CodeAttributeDeclarationCollection _customAttributes; - private CodeDirectiveCollection _startDirectives; - private CodeDirectiveCollection _endDirectives; - public string Name { - get => _name ?? string.Empty; - set => _name = value; + get => field ?? string.Empty; + set => field = value; } public MemberAttributes Attributes { get; set; } = MemberAttributes.Private | MemberAttributes.Final; public CodeAttributeDeclarationCollection CustomAttributes { - get => _customAttributes ??= new CodeAttributeDeclarationCollection(); - set => _customAttributes = value; + get => field ??= new CodeAttributeDeclarationCollection(); + set => field = value; } public CodeLinePragma LinePragma { get; set; } public CodeCommentStatementCollection Comments { get; } = new CodeCommentStatementCollection(); - public CodeDirectiveCollection StartDirectives => _startDirectives ??= new CodeDirectiveCollection(); + public CodeDirectiveCollection StartDirectives => field ??= new CodeDirectiveCollection(); - public CodeDirectiveCollection EndDirectives => _endDirectives ??= new CodeDirectiveCollection(); + public CodeDirectiveCollection EndDirectives => field ??= new CodeDirectiveCollection(); } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeOfExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeOfExpression.cs index bb7f4f3430d407..651edbb538cfef 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeOfExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeOfExpression.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeTypeOfExpression : CodeExpression { - private CodeTypeReference _type; - public CodeTypeOfExpression() { } public CodeTypeOfExpression(CodeTypeReference type) @@ -26,8 +24,8 @@ public CodeTypeOfExpression(Type type) public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameter.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameter.cs index 7c8a0148788574..124df444434ae9 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameter.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeParameter.cs @@ -6,8 +6,6 @@ namespace System.CodeDom public class CodeTypeParameter : CodeObject { private string _name; - private CodeAttributeDeclarationCollection _customAttributes; - private CodeTypeReferenceCollection _constraints; public CodeTypeParameter() { } @@ -22,9 +20,9 @@ public string Name set => _name = value; } - public CodeTypeReferenceCollection Constraints => _constraints ??= new CodeTypeReferenceCollection(); + public CodeTypeReferenceCollection Constraints => field ??= new CodeTypeReferenceCollection(); - public CodeAttributeDeclarationCollection CustomAttributes => _customAttributes ??= new CodeAttributeDeclarationCollection(); + public CodeAttributeDeclarationCollection CustomAttributes => field ??= new CodeAttributeDeclarationCollection(); public bool HasConstructorConstraint { get; set; } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeReferenceExpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeReferenceExpression.cs index 338c64fb5c5600..d8d04e54fa57f2 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeReferenceExpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeTypeReferenceExpression.cs @@ -5,8 +5,6 @@ namespace System.CodeDom { public class CodeTypeReferenceExpression : CodeExpression { - private CodeTypeReference _type; - public CodeTypeReferenceExpression() { } public CodeTypeReferenceExpression(CodeTypeReference type) @@ -26,8 +24,8 @@ public CodeTypeReferenceExpression(Type type) public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/CodeVariableDeclarationStatement.cs b/src/libraries/System.CodeDom/src/System/CodeDom/CodeVariableDeclarationStatement.cs index 7672c8eb42f6c1..66efd3549b6bc6 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/CodeVariableDeclarationStatement.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/CodeVariableDeclarationStatement.cs @@ -5,9 +5,6 @@ namespace System.CodeDom { public class CodeVariableDeclarationStatement : CodeStatement { - private CodeTypeReference _type; - private string _name; - public CodeVariableDeclarationStatement() { } public CodeVariableDeclarationStatement(CodeTypeReference type, string name) @@ -53,14 +50,14 @@ public CodeVariableDeclarationStatement(Type type, string name, CodeExpression i public string Name { - get => _name ?? string.Empty; - set => _name = value; + get => field ?? string.Empty; + set => field = value; } public CodeTypeReference Type { - get => _type ??= new CodeTypeReference(""); - set => _type = value; + get => field ??= new CodeTypeReference(""); + set => field = value; } } } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs index 59fb4c036dc800..f4a57a1dc34e44 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CompilerParameters.cs @@ -7,8 +7,6 @@ namespace System.CodeDom.Compiler { public partial class CompilerParameters { - private TempFileCollection _tempFiles; - public CompilerParameters() : this(null, null) { } @@ -60,8 +58,8 @@ public CompilerParameters(string[] assemblyNames, string outputName, bool includ public TempFileCollection TempFiles { - get => _tempFiles ??= new TempFileCollection(); - set => _tempFiles = value; + get => field ??= new TempFileCollection(); + set => field = value; } public bool IncludeDebugInformation { get; set; } diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs b/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs index cf6cd07050d7a8..0cd96716768635 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/codemethodreferenceexpression.cs @@ -5,9 +5,6 @@ namespace System.CodeDom { public class CodeMethodReferenceExpression : CodeExpression { - private string _methodName; - private CodeTypeReferenceCollection _typeArguments; - public CodeMethodReferenceExpression() { } public CodeMethodReferenceExpression(CodeExpression targetObject, string methodName) @@ -30,10 +27,10 @@ public CodeMethodReferenceExpression(CodeExpression targetObject, string methodN public string MethodName { - get => _methodName ?? string.Empty; - set => _methodName = value; + get => field ?? string.Empty; + set => field = value; } - public CodeTypeReferenceCollection TypeArguments => _typeArguments ??= new CodeTypeReferenceCollection(); + public CodeTypeReferenceCollection TypeArguments => field ??= new CodeTypeReferenceCollection(); } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs index fc75f69a594d6c..394f31ab522289 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Builder.cs @@ -1185,11 +1185,6 @@ internal sealed class ImmutableListBuilderDebuggerProxy /// private readonly ImmutableList.Builder _list; - /// - /// The simple view of the collection. - /// - private T[]? _cachedContents; - /// /// Initializes a new instance of the class. /// @@ -1204,6 +1199,6 @@ public ImmutableListBuilderDebuggerProxy(ImmutableList.Builder builder) /// Gets a simple debugger-viewable list. /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public T[] Contents => _cachedContents ??= _list.ToArray(_list.Count); + public T[] Contents => field ??= _list.ToArray(_list.Count); } } diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs index 22bb48f8a1c2f0..724bd70d5bdde8 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/CaseInsensitiveHashCodeProvider.cs @@ -12,7 +12,6 @@ namespace System.Collections [Obsolete("CaseInsensitiveHashCodeProvider has been deprecated. Use StringComparer instead.")] public class CaseInsensitiveHashCodeProvider : IHashCodeProvider { - private static CaseInsensitiveHashCodeProvider? s_invariantCaseInsensitiveHashCodeProvider; private readonly CompareInfo _compareInfo; public CaseInsensitiveHashCodeProvider() @@ -29,7 +28,7 @@ public CaseInsensitiveHashCodeProvider(CultureInfo culture) public static CaseInsensitiveHashCodeProvider Default => new CaseInsensitiveHashCodeProvider(); - public static CaseInsensitiveHashCodeProvider DefaultInvariant => s_invariantCaseInsensitiveHashCodeProvider ??= new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture); + public static CaseInsensitiveHashCodeProvider DefaultInvariant => field ??= new CaseInsensitiveHashCodeProvider(CultureInfo.InvariantCulture); public int GetHashCode(object obj) { diff --git a/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs b/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs index 3cf850e4966c8b..5651d5ff2a3b16 100644 --- a/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs +++ b/src/libraries/System.Collections.NonGeneric/src/System/Collections/ReadOnlyCollectionBase.cs @@ -16,9 +16,7 @@ namespace System.Collections // Useful base class for typed readonly collections where items derive from object public abstract class ReadOnlyCollectionBase : ICollection { - private ArrayList? _list; - - protected ArrayList InnerList => _list ??= new ArrayList(); + protected ArrayList InnerList => field ??= new ArrayList(); public virtual int Count { diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs b/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs index 689fec12f12d6c..8eec08838be6ba 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/OrderedDictionary.cs @@ -52,11 +52,6 @@ class OrderedDictionary : /// Multiplier used on 64-bit to enable faster % operations. private ulong _fastModMultiplier; - /// Lazily-initialized wrapper collection that serves up only the keys, in order. - private KeyCollection? _keys; - /// Lazily-initialized wrapper collection that serves up only the values, in order. - private ValueCollection? _values; - /// /// Initializes a new instance of the class that is empty, /// has the default initial capacity, and uses the default equality comparer for the key type. @@ -257,7 +252,7 @@ public IEqualityComparer Comparer bool IList.IsFixedSize => false; /// Gets a collection containing the keys in the . - public KeyCollection Keys => _keys ??= new(this); + public KeyCollection Keys => field ??= new(this); /// IEnumerable IReadOnlyDictionary.Keys => Keys; @@ -269,7 +264,7 @@ public IEqualityComparer Comparer ICollection IDictionary.Keys => Keys; /// Gets a collection containing the values in the . - public ValueCollection Values => _values ??= new(this); + public ValueCollection Values => field ??= new(this); /// IEnumerable IReadOnlyDictionary.Values => Values; diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs index c5f7c7e7e0c28d..fb3baf19446928 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs @@ -30,11 +30,6 @@ public class PriorityQueue /// private readonly IComparer? _comparer; - /// - /// Lazily-initialized collection used to expose the contents of the queue. - /// - private UnorderedItemsCollection? _unorderedItems; - /// /// The number of nodes in the heap. /// @@ -188,7 +183,7 @@ public PriorityQueue(IEnumerable<(TElement Element, TPriority Priority)> items, /// The enumeration does not order items by priority, since that would require N * log(N) time and N space. /// Items are instead enumerated following the internal array heap layout. /// - public UnorderedItemsCollection UnorderedItems => _unorderedItems ??= new UnorderedItemsCollection(this); + public UnorderedItemsCollection UnorderedItems => field ??= new UnorderedItemsCollection(this); /// /// Adds the specified element with associated priority to the . diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs index 58adef95a8005b..3a1cad0370cfcc 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionMemberExportDefinition.cs @@ -12,7 +12,6 @@ internal sealed class ReflectionMemberExportDefinition : ExportDefinition, IComp private readonly LazyMemberInfo _member; private readonly ExportDefinition _exportDefinition; private readonly ICompositionElement? _origin; - private IDictionary? _metadata; public ReflectionMemberExportDefinition(LazyMemberInfo member, ExportDefinition exportDefinition, ICompositionElement? origin) { @@ -33,7 +32,7 @@ public LazyMemberInfo ExportingLazyMember get { return _member; } } - public override IDictionary Metadata => _metadata ??= _exportDefinition.Metadata.AsReadOnly(); + public override IDictionary Metadata => field ??= _exportDefinition.Metadata.AsReadOnly(); string ICompositionElement.DisplayName { diff --git a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/CategoryAttribute.cs b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/CategoryAttribute.cs index fc06665da5ecfc..8f6560b821dc2e 100644 --- a/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/CategoryAttribute.cs +++ b/src/libraries/System.ComponentModel.Primitives/src/System/ComponentModel/CategoryAttribute.cs @@ -12,21 +12,6 @@ namespace System.ComponentModel [AttributeUsage(AttributeTargets.All)] public class CategoryAttribute : Attribute { - private static CategoryAttribute? s_action; - private static CategoryAttribute? s_appearance; - private static CategoryAttribute? s_asynchronous; - private static CategoryAttribute? s_behavior; - private static CategoryAttribute? s_data; - private static CategoryAttribute? s_design; - private static CategoryAttribute? s_dragDrop; - private static CategoryAttribute? s_defAttr; - private static CategoryAttribute? s_focus; - private static CategoryAttribute? s_format; - private static CategoryAttribute? s_key; - private static CategoryAttribute? s_layout; - private static CategoryAttribute? s_mouse; - private static CategoryAttribute? s_windowStyle; - private volatile bool _localized; private readonly object _locker = new object(); @@ -39,114 +24,72 @@ public class CategoryAttribute : Attribute /// /// Gets the action category attribute. /// - public static CategoryAttribute Action - { - get => s_action ??= new CategoryAttribute(nameof(Action)); - } + public static CategoryAttribute Action => field ??= new CategoryAttribute(nameof(Action)); /// /// Gets the appearance category attribute. /// - public static CategoryAttribute Appearance - { - get => s_appearance ??= new CategoryAttribute(nameof(Appearance)); - } + public static CategoryAttribute Appearance => field ??= new CategoryAttribute(nameof(Appearance)); /// /// Gets the asynchronous category attribute. /// - public static CategoryAttribute Asynchronous - { - get => s_asynchronous ??= new CategoryAttribute(nameof(Asynchronous)); - } + public static CategoryAttribute Asynchronous => field ??= new CategoryAttribute(nameof(Asynchronous)); /// /// Gets the behavior category attribute. /// - public static CategoryAttribute Behavior - { - get => s_behavior ??= new CategoryAttribute(nameof(Behavior)); - } + public static CategoryAttribute Behavior => field ??= new CategoryAttribute(nameof(Behavior)); /// /// Gets the data category attribute. /// - public static CategoryAttribute Data - { - get => s_data ??= new CategoryAttribute(nameof(Data)); - } + public static CategoryAttribute Data => field ??= new CategoryAttribute(nameof(Data)); /// /// Gets the default category attribute. /// - public static CategoryAttribute Default - { - get => s_defAttr ??= new CategoryAttribute(); - } + public static CategoryAttribute Default => field ??= new CategoryAttribute(); /// /// Gets the design category attribute. /// - public static CategoryAttribute Design - { - get => s_design ??= new CategoryAttribute(nameof(Design)); - } + public static CategoryAttribute Design => field ??= new CategoryAttribute(nameof(Design)); /// /// Gets the drag and drop category attribute. /// - public static CategoryAttribute DragDrop - { - get => s_dragDrop ??= new CategoryAttribute(nameof(DragDrop)); - } + public static CategoryAttribute DragDrop => field ??= new CategoryAttribute(nameof(DragDrop)); /// /// Gets the focus category attribute. /// - public static CategoryAttribute Focus - { - get => s_focus ??= new CategoryAttribute(nameof(Focus)); - } + public static CategoryAttribute Focus => field ??= new CategoryAttribute(nameof(Focus)); /// /// Gets the format category attribute. /// - public static CategoryAttribute Format - { - get => s_format ??= new CategoryAttribute(nameof(Format)); - } + public static CategoryAttribute Format => field ??= new CategoryAttribute(nameof(Format)); /// /// Gets the keyboard category attribute. /// - public static CategoryAttribute Key - { - get => s_key ??= new CategoryAttribute(nameof(Key)); - } + public static CategoryAttribute Key => field ??= new CategoryAttribute(nameof(Key)); /// /// Gets the layout category attribute. /// - public static CategoryAttribute Layout - { - get => s_layout ??= new CategoryAttribute(nameof(Layout)); - } + public static CategoryAttribute Layout => field ??= new CategoryAttribute(nameof(Layout)); /// /// Gets the mouse category attribute. /// - public static CategoryAttribute Mouse - { - get => s_mouse ??= new CategoryAttribute(nameof(Mouse)); - } + public static CategoryAttribute Mouse => field ??= new CategoryAttribute(nameof(Mouse)); /// /// Gets the window style category attribute. /// - public static CategoryAttribute WindowStyle - { - get => s_windowStyle ??= new CategoryAttribute(nameof(WindowStyle)); - } + public static CategoryAttribute WindowStyle => field ??= new CategoryAttribute(nameof(WindowStyle)); /// /// Initializes a new instance of the diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index 2185bc5d1a7cbf..26269b11d1e300 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -12,16 +12,11 @@ namespace System.ComponentModel.Design /// public abstract class DesignerOptionService : IDesignerOptionService { - private DesignerOptionCollection? _options; - /// /// Returns the options collection for this service. There is /// always a global options collection that contains child collections. /// - public DesignerOptionCollection Options - { - get => _options ??= new DesignerOptionCollection(this, null, string.Empty, null); - } + public DesignerOptionCollection Options => field ??= new DesignerOptionCollection(this, null, string.Empty, null); /// /// Creates a new DesignerOptionCollection with the given name, and adds it to diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemFilterAttribute.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemFilterAttribute.cs index 9dd92762ac76eb..88704ecb6ee819 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemFilterAttribute.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ToolboxItemFilterAttribute.cs @@ -43,8 +43,6 @@ namespace System.ComponentModel [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class ToolboxItemFilterAttribute : Attribute { - private string? _typeId; - /// /// Initializes a new ToolboxItemFilterAttribute with the provide filter string and a filter type of /// "Allow". @@ -78,7 +76,7 @@ public ToolboxItemFilterAttribute(string filterString, ToolboxItemFilterType fil /// The unique identifier for this attribute. All ToolboxItemFilterAttributes with the same filter string /// are considered the same, so they return the same TypeId. /// - public override object TypeId => _typeId ??= GetType().FullName + FilterString; + public override object TypeId => field ??= GetType().FullName + FilterString; public override bool Equals([NotNullWhen(true)] object? obj) { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs index 9d0a3338a38edf..e2b324c801cdd5 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessModule.cs @@ -15,7 +15,6 @@ public class ProcessModule : Component { private readonly string _fileName; private readonly string _moduleName; - private FileVersionInfo? _fileVersionInfo; internal ProcessModule(string fileName, string moduleName) { @@ -55,7 +54,7 @@ internal ProcessModule(string fileName, string moduleName) /// /// Returns version information about the module. /// - public FileVersionInfo FileVersionInfo => _fileVersionInfo ??= FileVersionInfo.GetVersionInfo(_fileName); + public FileVersionInfo FileVersionInfo => field ??= FileVersionInfo.GetVersionInfo(_fileName); public override string ToString() => $"{base.ToString()} ({ModuleName})"; } diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs index 52c35b964b8845..d8625f32fcfc4e 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/Trace.cs @@ -19,12 +19,10 @@ private Trace() { } - private static CorrelationManager? s_correlationManager; - public static CorrelationManager CorrelationManager => - Volatile.Read(ref s_correlationManager) ?? - Interlocked.CompareExchange(ref s_correlationManager, new CorrelationManager(), null) ?? - s_correlationManager; + Volatile.Read(ref field) ?? + Interlocked.CompareExchange(ref field, new(), null) ?? + field; /// /// Gets the collection of listeners that is monitoring the trace output. diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs index 6d314bda14124f..a4afc07f3f33b2 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceEventCache.cs @@ -13,7 +13,6 @@ public partial class TraceEventCache { private long _timeStamp = -1; private DateTime _dateTime = DateTime.MinValue; - private string? _stackTrace; public DateTime DateTime { @@ -51,7 +50,7 @@ public long Timestamp } } - public string Callstack => _stackTrace ??= Environment.StackTrace; + public string Callstack => field ??= Environment.StackTrace; public Stack LogicalOperationStack { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs index 0b9975b608d72e..c133a2a547827b 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceInternal.cs @@ -41,7 +41,6 @@ public override void OnIndentSizeChanged(int indentSize) public override void WriteLine(string? message) { TraceInternal.WriteLine(message); } } - private static volatile string? s_appName; private static volatile TraceListenerCollection? s_listeners; private static volatile bool s_autoFlush; private static volatile bool s_useGlobalLock; @@ -81,7 +80,7 @@ public static TraceListenerCollection Listeners } } - internal static string AppName => s_appName ??= Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty; + internal static string AppName => field ??= Assembly.GetEntryAssembly()?.GetName().Name ?? string.Empty; public static bool AutoFlush { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs index d739be5250b346..a23cab3659aa3f 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListener.cs @@ -21,7 +21,6 @@ public abstract class TraceListener : MarshalByRefObject, IDisposable private int _indentSize = 4; private TraceOptions _traceOptions = TraceOptions.None; private bool _needIndent = true; - private StringDictionary? _attributes; private string? _listenerName; private TraceFilter? _filter; @@ -42,7 +41,7 @@ protected TraceListener(string? name) _listenerName = name; } - public StringDictionary Attributes => _attributes ??= new StringDictionary(); + public StringDictionary Attributes => field ??= new StringDictionary(); /// /// Gets or sets a name for this . diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs index 3b83e360ee28a9..01c1eedce5df1a 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs @@ -8,7 +8,6 @@ namespace System.DirectoryServices.Protocols { internal class LdapAsyncResult : IAsyncResult { - private LdapAsyncWaitHandle _asyncWaitHandle; internal AsyncCallback _callback; internal bool _completed; internal ManualResetEvent _manualResetEvent; @@ -26,10 +25,7 @@ public LdapAsyncResult(AsyncCallback callbackRoutine, object state, bool partial object IAsyncResult.AsyncState => _stateObject; - WaitHandle IAsyncResult.AsyncWaitHandle - { - get => _asyncWaitHandle ??= new LdapAsyncWaitHandle(_manualResetEvent.SafeWaitHandle); - } + WaitHandle IAsyncResult.AsyncWaitHandle => field ??= new LdapAsyncWaitHandle(_manualResetEvent.SafeWaitHandle); bool IAsyncResult.CompletedSynchronously => false; diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxGlobalExtendedAttributesTarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxGlobalExtendedAttributesTarEntry.cs index 9dc572f8c1c1e4..62a0cf620bdfee 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxGlobalExtendedAttributesTarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxGlobalExtendedAttributesTarEntry.cs @@ -11,8 +11,6 @@ namespace System.Formats.Tar /// public sealed class PaxGlobalExtendedAttributesTarEntry : PosixTarEntry { - private ReadOnlyDictionary? _readOnlyGlobalExtendedAttributes; - // Constructor used when reading an existing archive. internal PaxGlobalExtendedAttributesTarEntry(TarHeader header, TarReader readerOfOrigin) : base(header, readerOfOrigin, TarEntryFormat.Pax) @@ -34,7 +32,7 @@ public PaxGlobalExtendedAttributesTarEntry(IEnumerable /// Returns the global extended attributes stored in this entry. /// - public IReadOnlyDictionary GlobalExtendedAttributes => _readOnlyGlobalExtendedAttributes ??= _header.ExtendedAttributes.AsReadOnly(); + public IReadOnlyDictionary GlobalExtendedAttributes => field ??= _header.ExtendedAttributes.AsReadOnly(); // Determines if the current instance's entry type supports setting a data stream. internal override bool IsDataStreamSetterSupported() => false; diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs index 30397b03b27ad0..4f1e3f0b4fe022 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/PaxTarEntry.cs @@ -12,8 +12,6 @@ namespace System.Formats.Tar /// public sealed class PaxTarEntry : PosixTarEntry { - private ReadOnlyDictionary? _readOnlyExtendedAttributes; - // Constructor called when reading a TarEntry from a TarReader. internal PaxTarEntry(TarHeader header, TarReader readerOfOrigin) : base(header, readerOfOrigin, TarEntryFormat.Pax) @@ -122,7 +120,7 @@ public PaxTarEntry(TarEntry other) /// File length, under the name size, as an . /// /// - public IReadOnlyDictionary ExtendedAttributes => _readOnlyExtendedAttributes ??= _header.ExtendedAttributes.AsReadOnly(); + public IReadOnlyDictionary ExtendedAttributes => field ??= _header.ExtendedAttributes.AsReadOnly(); // Determines if the current instance's entry type supports setting a data stream. internal override bool IsDataStreamSetterSupported() => EntryType == TarEntryType.RegularFile; diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index e5a8618b814cfc..498d989adffa54 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -31,7 +31,6 @@ internal sealed partial class SerialStream : Stream private readonly byte[] _tempBuf = new byte[1]; private Task _ioLoop; private readonly object _ioLoopLock = new object(); - private bool _hasCancelledTasksToProcess; // Use a Queue with locking instead of ConcurrentQueue because ConcurrentQueue preserves segments for // observation when using TryPeek(). These segments will not clear out references after a dequeue // and as a result they hold on to SerialStreamIORequest instances so that they cannot be GC'ed. @@ -362,8 +361,8 @@ internal byte ParityReplace private bool HasCancelledTasksToProcess { - get => Volatile.Read(ref _hasCancelledTasksToProcess); - set => Volatile.Write(ref _hasCancelledTasksToProcess, value); + get => Volatile.Read(ref field); + set => Volatile.Write(ref field, value); } internal void DiscardInBuffer() diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Common/CachedReflectionInfo.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Common/CachedReflectionInfo.cs index 76f8ba91925510..c5bf8dd8d25604 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Common/CachedReflectionInfo.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Common/CachedReflectionInfo.cs @@ -9,158 +9,45 @@ namespace System.Linq.Expressions { internal static partial class CachedReflectionInfo { - private static ConstructorInfo? s_Nullable_Boolean_Ctor; - - public static ConstructorInfo Nullable_Boolean_Ctor - => s_Nullable_Boolean_Ctor ??= typeof(bool?).GetConstructor(new[] { typeof(bool) })!; - - private static ConstructorInfo? s_Decimal_Ctor_Int32; - public static ConstructorInfo Decimal_Ctor_Int32 => - s_Decimal_Ctor_Int32 ??= typeof(decimal).GetConstructor(new[] { typeof(int) })!; - - private static ConstructorInfo? s_Decimal_Ctor_UInt32; - public static ConstructorInfo Decimal_Ctor_UInt32 => - s_Decimal_Ctor_UInt32 ??= typeof(decimal).GetConstructor(new[] { typeof(uint) })!; - - private static ConstructorInfo? s_Decimal_Ctor_Int64; - public static ConstructorInfo Decimal_Ctor_Int64 => - s_Decimal_Ctor_Int64 ??= typeof(decimal).GetConstructor(new[] { typeof(long) })!; - - private static ConstructorInfo? s_Decimal_Ctor_UInt64; - public static ConstructorInfo Decimal_Ctor_UInt64 => - s_Decimal_Ctor_UInt64 ??= typeof(decimal).GetConstructor(new[] { typeof(ulong) })!; - - private static ConstructorInfo? s_Decimal_Ctor_Int32_Int32_Int32_Bool_Byte; - public static ConstructorInfo Decimal_Ctor_Int32_Int32_Int32_Bool_Byte => - s_Decimal_Ctor_Int32_Int32_Int32_Bool_Byte ??= typeof(decimal).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) })!; - - private static FieldInfo? s_Decimal_One; - public static FieldInfo Decimal_One => - s_Decimal_One ??= typeof(decimal).GetField(nameof(decimal.One))!; - - private static FieldInfo? s_Decimal_MinusOne; - public static FieldInfo Decimal_MinusOne => - s_Decimal_MinusOne ??= typeof(decimal).GetField(nameof(decimal.MinusOne))!; - - private static FieldInfo? s_Decimal_MinValue; - public static FieldInfo Decimal_MinValue => - s_Decimal_MinValue ??= typeof(decimal).GetField(nameof(decimal.MinValue))!; - - private static FieldInfo? s_Decimal_MaxValue; - public static FieldInfo Decimal_MaxValue => - s_Decimal_MaxValue ??= typeof(decimal).GetField(nameof(decimal.MaxValue))!; - - private static FieldInfo? s_Decimal_Zero; - public static FieldInfo Decimal_Zero => - s_Decimal_Zero ??= typeof(decimal).GetField(nameof(decimal.Zero))!; - - private static FieldInfo? s_DateTime_MinValue; - public static FieldInfo DateTime_MinValue => - s_DateTime_MinValue ??= typeof(DateTime).GetField(nameof(DateTime.MinValue))!; - - private static MethodInfo? s_MethodBase_GetMethodFromHandle_RuntimeMethodHandle; - public static MethodInfo MethodBase_GetMethodFromHandle_RuntimeMethodHandle => - s_MethodBase_GetMethodFromHandle_RuntimeMethodHandle ??= typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new[] { typeof(RuntimeMethodHandle) })!; - - private static MethodInfo? s_MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle; - public static MethodInfo MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle => - s_MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle ??= typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) })!; - - private static MethodInfo? s_MethodInfo_CreateDelegate_Type_Object; - public static MethodInfo MethodInfo_CreateDelegate_Type_Object => - s_MethodInfo_CreateDelegate_Type_Object ??= typeof(MethodInfo).GetMethod(nameof(MethodInfo.CreateDelegate), new[] { typeof(Type), typeof(object) })!; - - private static MethodInfo? s_String_op_Equality_String_String; - public static MethodInfo String_op_Equality_String_String => - s_String_op_Equality_String_String ??= typeof(string).GetMethod("op_Equality", new[] { typeof(string), typeof(string) })!; - - private static MethodInfo? s_String_Equals_String_String; - public static MethodInfo String_Equals_String_String => - s_String_Equals_String_String ??= typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(string) })!; - - private static MethodInfo? s_DictionaryOfStringInt32_Add_String_Int32; - public static MethodInfo DictionaryOfStringInt32_Add_String_Int32 => - s_DictionaryOfStringInt32_Add_String_Int32 ??= typeof(Dictionary).GetMethod(nameof(Dictionary.Add), new[] { typeof(string), typeof(int) })!; - - private static ConstructorInfo? s_DictionaryOfStringInt32_Ctor_Int32; - public static ConstructorInfo DictionaryOfStringInt32_Ctor_Int32 => - s_DictionaryOfStringInt32_Ctor_Int32 ??= typeof(Dictionary).GetConstructor(new[] { typeof(int) })!; - - private static MethodInfo? s_Type_GetTypeFromHandle; - public static MethodInfo Type_GetTypeFromHandle => - s_Type_GetTypeFromHandle ??= typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle))!; - - private static MethodInfo? s_Object_GetType; - public static MethodInfo Object_GetType => - s_Object_GetType ??= typeof(object).GetMethod(nameof(object.GetType))!; - - private static MethodInfo? s_Decimal_op_Implicit_Byte; - public static MethodInfo Decimal_op_Implicit_Byte => - s_Decimal_op_Implicit_Byte ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(byte) })!; - - private static MethodInfo? s_Decimal_op_Implicit_SByte; - public static MethodInfo Decimal_op_Implicit_SByte => - s_Decimal_op_Implicit_SByte ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(sbyte) })!; - - private static MethodInfo? s_Decimal_op_Implicit_Int16; - public static MethodInfo Decimal_op_Implicit_Int16 => - s_Decimal_op_Implicit_Int16 ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(short) })!; - - private static MethodInfo? s_Decimal_op_Implicit_UInt16; - public static MethodInfo Decimal_op_Implicit_UInt16 => - s_Decimal_op_Implicit_UInt16 ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(ushort) })!; - - private static MethodInfo? s_Decimal_op_Implicit_Int32; - public static MethodInfo Decimal_op_Implicit_Int32 => - s_Decimal_op_Implicit_Int32 ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(int) })!; - - private static MethodInfo? s_Decimal_op_Implicit_UInt32; - public static MethodInfo Decimal_op_Implicit_UInt32 => - s_Decimal_op_Implicit_UInt32 ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(uint) })!; - - private static MethodInfo? s_Decimal_op_Implicit_Int64; - public static MethodInfo Decimal_op_Implicit_Int64 => - s_Decimal_op_Implicit_Int64 ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(long) })!; - - private static MethodInfo? s_Decimal_op_Implicit_UInt64; - public static MethodInfo Decimal_op_Implicit_UInt64 => - s_Decimal_op_Implicit_UInt64 ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(ulong) })!; - - private static MethodInfo? s_Decimal_op_Implicit_Char; - public static MethodInfo Decimal_op_Implicit_Char => - s_Decimal_op_Implicit_Char ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(char) })!; - - private static MethodInfo? s_Math_Pow_Double_Double; - public static MethodInfo Math_Pow_Double_Double => - s_Math_Pow_Double_Double ??= typeof(Math).GetMethod(nameof(Math.Pow), new[] { typeof(double), typeof(double) })!; + public static ConstructorInfo Nullable_Boolean_Ctor => field ??= typeof(bool?).GetConstructor(new[] { typeof(bool) })!; + public static ConstructorInfo Decimal_Ctor_Int32 => field ??= typeof(decimal).GetConstructor(new[] { typeof(int) })!; + public static ConstructorInfo Decimal_Ctor_UInt32 => field ??= typeof(decimal).GetConstructor(new[] { typeof(uint) })!; + public static ConstructorInfo Decimal_Ctor_Int64 => field ??= typeof(decimal).GetConstructor(new[] { typeof(long) })!; + public static ConstructorInfo Decimal_Ctor_UInt64 => field ??= typeof(decimal).GetConstructor(new[] { typeof(ulong) })!; + public static ConstructorInfo Decimal_Ctor_Int32_Int32_Int32_Bool_Byte => field ??= typeof(decimal).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) })!; + public static FieldInfo Decimal_One => field ??= typeof(decimal).GetField(nameof(decimal.One))!; + public static FieldInfo Decimal_MinusOne => field ??= typeof(decimal).GetField(nameof(decimal.MinusOne))!; + public static FieldInfo Decimal_MinValue => field ??= typeof(decimal).GetField(nameof(decimal.MinValue))!; + public static FieldInfo Decimal_MaxValue => field ??= typeof(decimal).GetField(nameof(decimal.MaxValue))!; + public static FieldInfo Decimal_Zero => field ??= typeof(decimal).GetField(nameof(decimal.Zero))!; + public static FieldInfo DateTime_MinValue => field ??= typeof(DateTime).GetField(nameof(DateTime.MinValue))!; + public static MethodInfo MethodBase_GetMethodFromHandle_RuntimeMethodHandle => field ??= typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new[] { typeof(RuntimeMethodHandle) })!; + public static MethodInfo MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle => field ??= typeof(MethodBase).GetMethod(nameof(MethodBase.GetMethodFromHandle), new[] { typeof(RuntimeMethodHandle), typeof(RuntimeTypeHandle) })!; + public static MethodInfo MethodInfo_CreateDelegate_Type_Object => field ??= typeof(MethodInfo).GetMethod(nameof(MethodInfo.CreateDelegate), new[] { typeof(Type), typeof(object) })!; + public static MethodInfo String_op_Equality_String_String => field ??= typeof(string).GetMethod("op_Equality", new[] { typeof(string), typeof(string) })!; + public static MethodInfo String_Equals_String_String => field ??= typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(string) })!; + public static MethodInfo DictionaryOfStringInt32_Add_String_Int32 => field ??= typeof(Dictionary).GetMethod(nameof(Dictionary.Add), new[] { typeof(string), typeof(int) })!; + public static ConstructorInfo DictionaryOfStringInt32_Ctor_Int32 => field ??= typeof(Dictionary).GetConstructor(new[] { typeof(int) })!; + public static MethodInfo Type_GetTypeFromHandle => field ??= typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle))!; + public static MethodInfo Object_GetType => field ??= typeof(object).GetMethod(nameof(object.GetType))!; + public static MethodInfo Decimal_op_Implicit_Byte => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(byte) })!; + public static MethodInfo Decimal_op_Implicit_SByte => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(sbyte) })!; + public static MethodInfo Decimal_op_Implicit_Int16 => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(short) })!; + public static MethodInfo Decimal_op_Implicit_UInt16 => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(ushort) })!; + public static MethodInfo Decimal_op_Implicit_Int32 => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(int) })!; + public static MethodInfo Decimal_op_Implicit_UInt32 => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(uint) })!; + public static MethodInfo Decimal_op_Implicit_Int64 => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(long) })!; + public static MethodInfo Decimal_op_Implicit_UInt64 => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(ulong) })!; + public static MethodInfo Decimal_op_Implicit_Char => field ??= typeof(decimal).GetMethod("op_Implicit", new[] { typeof(char) })!; + public static MethodInfo Math_Pow_Double_Double => field ??= typeof(Math).GetMethod(nameof(Math.Pow), new[] { typeof(double), typeof(double) })!; // Closure and RuntimeOps helpers are used only in the compiler. - private static ConstructorInfo? s_Closure_ObjectArray_ObjectArray; - public static ConstructorInfo Closure_ObjectArray_ObjectArray => - s_Closure_ObjectArray_ObjectArray ??= typeof(Closure).GetConstructor(new[] { typeof(object[]), typeof(object[]) })!; - - private static FieldInfo? s_Closure_Constants; - public static FieldInfo Closure_Constants => - s_Closure_Constants ??= typeof(Closure).GetField(nameof(Closure.Constants))!; - - private static FieldInfo? s_Closure_Locals; - public static FieldInfo Closure_Locals => - s_Closure_Locals ??= typeof(Closure).GetField(nameof(Closure.Locals))!; - - private static MethodInfo? s_RuntimeOps_CreateRuntimeVariables_ObjectArray_Int64Array; - public static MethodInfo RuntimeOps_CreateRuntimeVariables_ObjectArray_Int64Array => - s_RuntimeOps_CreateRuntimeVariables_ObjectArray_Int64Array ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.CreateRuntimeVariables), new[] { typeof(object[]), typeof(long[]) })!; - - private static MethodInfo? s_RuntimeOps_CreateRuntimeVariables; - public static MethodInfo RuntimeOps_CreateRuntimeVariables => - s_RuntimeOps_CreateRuntimeVariables ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.CreateRuntimeVariables), Type.EmptyTypes)!; - - private static MethodInfo? s_RuntimeOps_MergeRuntimeVariables; - public static MethodInfo RuntimeOps_MergeRuntimeVariables => - s_RuntimeOps_MergeRuntimeVariables ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.MergeRuntimeVariables))!; - - private static MethodInfo? s_RuntimeOps_Quote; - public static MethodInfo RuntimeOps_Quote => - s_RuntimeOps_Quote ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.Quote))!; + public static ConstructorInfo Closure_ObjectArray_ObjectArray => field ??= typeof(Closure).GetConstructor(new[] { typeof(object[]), typeof(object[]) })!; + public static FieldInfo Closure_Constants => field ??= typeof(Closure).GetField(nameof(Closure.Constants))!; + public static FieldInfo Closure_Locals => field ??= typeof(Closure).GetField(nameof(Closure.Locals))!; + public static MethodInfo RuntimeOps_CreateRuntimeVariables_ObjectArray_Int64Array => field ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.CreateRuntimeVariables), new[] { typeof(object[]), typeof(long[]) })!; + public static MethodInfo RuntimeOps_CreateRuntimeVariables => field ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.CreateRuntimeVariables), Type.EmptyTypes)!; + public static MethodInfo RuntimeOps_MergeRuntimeVariables => field ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.MergeRuntimeVariables))!; + public static MethodInfo RuntimeOps_Quote => field ??= typeof(RuntimeOps).GetMethod(nameof(RuntimeOps.Quote))!; } } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs index 2f4d6e40c7b1cf..ccefd14a9a2e9f 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ControlFlowInstructions.cs @@ -47,9 +47,7 @@ public override string ToString() internal sealed class BranchFalseInstruction : OffsetInstruction { - private static Instruction[]? s_cache; - - public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize]; + public override Instruction[] Cache => field ??= new Instruction[CacheSize]; public override string InstructionName => "BranchFalse"; public override int ConsumedStack => 1; @@ -69,9 +67,7 @@ public override int Run(InterpretedFrame frame) internal sealed class BranchTrueInstruction : OffsetInstruction { - private static Instruction[]? s_cache; - - public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize]; + public override Instruction[] Cache => field ??= new Instruction[CacheSize]; public override string InstructionName => "BranchTrue"; public override int ConsumedStack => 1; @@ -91,9 +87,7 @@ public override int Run(InterpretedFrame frame) internal sealed class CoalescingBranchInstruction : OffsetInstruction { - private static Instruction[]? s_cache; - - public override Instruction[] Cache => s_cache ??= new Instruction[CacheSize]; + public override Instruction[] Cache => field ??= new Instruction[CacheSize]; public override string InstructionName => "CoalescingBranch"; public override int ConsumedStack => 1; diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs index 41df675b6aaf94..a68b7f24cb90dc 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteBinder.cs @@ -40,9 +40,7 @@ protected CallSiteBinder() private sealed class LambdaSignature where T : class { - private static LambdaSignature? s_instance; - - internal static LambdaSignature Instance => s_instance ??= new LambdaSignature(); + internal static LambdaSignature Instance => field ??= new LambdaSignature(); internal readonly ReadOnlyCollection Parameters; internal readonly LabelTarget ReturnLabel; diff --git a/src/libraries/System.Linq.Expressions/tests/ILReader/ILInstruction.cs b/src/libraries/System.Linq.Expressions/tests/ILReader/ILInstruction.cs index 5e65aa288dcb20..a80a7c0d3a9961 100644 --- a/src/libraries/System.Linq.Expressions/tests/ILReader/ILInstruction.cs +++ b/src/libraries/System.Linq.Expressions/tests/ILReader/ILInstruction.cs @@ -158,7 +158,6 @@ internal ShortInlineRInstruction(int offset, OpCode opCode, float value) public sealed class InlineFieldInstruction : ILInstruction { private readonly ITokenResolver _resolver; - private FieldInfo _field; internal InlineFieldInstruction(ITokenResolver resolver, int offset, OpCode opCode, int token) : base(offset, opCode) @@ -167,7 +166,7 @@ internal InlineFieldInstruction(ITokenResolver resolver, int offset, OpCode opCo Token = token; } - public FieldInfo Field => _field ??= _resolver.AsField(Token); + public FieldInfo Field => field ??= _resolver.AsField(Token); public int Token { get; } public override void Accept(ILInstructionVisitor visitor) => visitor.VisitInlineFieldInstruction(this); @@ -176,7 +175,6 @@ internal InlineFieldInstruction(ITokenResolver resolver, int offset, OpCode opCo public sealed class InlineMethodInstruction : ILInstruction { private readonly ITokenResolver _resolver; - private MethodBase _method; internal InlineMethodInstruction(int offset, OpCode opCode, int token, ITokenResolver resolver) : base(offset, opCode) @@ -185,7 +183,7 @@ internal InlineMethodInstruction(int offset, OpCode opCode, int token, ITokenRes Token = token; } - public MethodBase Method => _method ??= _resolver.AsMethod(Token); + public MethodBase Method => field ??= _resolver.AsMethod(Token); public int Token { get; } public override void Accept(ILInstructionVisitor visitor) => visitor.VisitInlineMethodInstruction(this); @@ -194,7 +192,6 @@ internal InlineMethodInstruction(int offset, OpCode opCode, int token, ITokenRes public sealed class InlineTypeInstruction : ILInstruction { private readonly ITokenResolver _resolver; - private Type _type; internal InlineTypeInstruction(int offset, OpCode opCode, int token, ITokenResolver resolver) : base(offset, opCode) @@ -203,7 +200,7 @@ internal InlineTypeInstruction(int offset, OpCode opCode, int token, ITokenResol Token = token; } - public Type Type => _type ??= _resolver.AsType(Token); + public Type Type => field ??= _resolver.AsType(Token); public int Token { get; } public override void Accept(ILInstructionVisitor visitor) => visitor.VisitInlineTypeInstruction(this); @@ -212,7 +209,6 @@ internal InlineTypeInstruction(int offset, OpCode opCode, int token, ITokenResol public sealed class InlineSigInstruction : ILInstruction { private readonly ITokenResolver _resolver; - private byte[] _signature; internal InlineSigInstruction(int offset, OpCode opCode, int token, ITokenResolver resolver) : base(offset, opCode) @@ -221,7 +217,7 @@ internal InlineSigInstruction(int offset, OpCode opCode, int token, ITokenResolv Token = token; } - public byte[] Signature => _signature ??= _resolver.AsSignature(Token); + public byte[] Signature => field ??= _resolver.AsSignature(Token); public int Token { get; } public override void Accept(ILInstructionVisitor visitor) => visitor.VisitInlineSigInstruction(this); @@ -230,7 +226,6 @@ internal InlineSigInstruction(int offset, OpCode opCode, int token, ITokenResolv public sealed class InlineTokInstruction : ILInstruction { private readonly ITokenResolver _resolver; - private MemberInfo _member; internal InlineTokInstruction(int offset, OpCode opCode, int token, ITokenResolver resolver) : base(offset, opCode) @@ -239,7 +234,7 @@ internal InlineTokInstruction(int offset, OpCode opCode, int token, ITokenResolv Token = token; } - public MemberInfo Member => _member ??= _resolver.AsMember(Token); + public MemberInfo Member => field ??= _resolver.AsMember(Token); public int Token { get; } public override void Accept(ILInstructionVisitor visitor) => visitor.VisitInlineTokInstruction(this); @@ -248,7 +243,6 @@ internal InlineTokInstruction(int offset, OpCode opCode, int token, ITokenResolv public sealed class InlineStringInstruction : ILInstruction { private readonly ITokenResolver _resolver; - private string _string; internal InlineStringInstruction(int offset, OpCode opCode, int token, ITokenResolver resolver) : base(offset, opCode) @@ -257,7 +251,7 @@ internal InlineStringInstruction(int offset, OpCode opCode, int token, ITokenRes Token = token; } - public string String => _string ??= _resolver.AsString(Token); + public string String => field ??= _resolver.AsString(Token); public int Token { get; } public override void Accept(ILInstructionVisitor visitor) => visitor.VisitInlineStringInstruction(this); diff --git a/src/libraries/System.Linq/src/System/Linq/DebugView.cs b/src/libraries/System.Linq/src/System/Linq/DebugView.cs index ddfb49cc3e2f9c..3cc23a1a542aaa 100644 --- a/src/libraries/System.Linq/src/System/Linq/DebugView.cs +++ b/src/libraries/System.Linq/src/System/Linq/DebugView.cs @@ -94,7 +94,6 @@ public object?[] Items internal sealed class SystemLinq_GroupingDebugView { private readonly Grouping _grouping; - private TElement[]? _cachedValues; public SystemLinq_GroupingDebugView(Grouping grouping) { @@ -105,13 +104,12 @@ public SystemLinq_GroupingDebugView(Grouping grouping) // The name of this property must alphabetically follow `Key` so the elements appear last in the display. [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public TElement[] Values => _cachedValues ??= _grouping.ToArray(); + public TElement[] Values => field ??= _grouping.ToArray(); } internal sealed class SystemLinq_LookupDebugView { private readonly ILookup _lookup; - private IGrouping[]? _cachedGroupings; public SystemLinq_LookupDebugView(ILookup lookup) { @@ -119,6 +117,6 @@ public SystemLinq_LookupDebugView(ILookup lookup) } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public IGrouping[] Groupings => _cachedGroupings ??= _lookup.ToArray(); + public IGrouping[] Groupings => field ??= _lookup.ToArray(); } } diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.netstandard.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.netstandard.cs index b69e47a3a25a70..62f29b6f58d2ce 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.netstandard.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpClientJsonExtensions.netstandard.cs @@ -8,8 +8,7 @@ namespace System.Net.Http.Json { public static partial class HttpClientJsonExtensions { - private static HttpMethod HttpPatch => s_httpPatch ??= new HttpMethod("PATCH"); - private static HttpMethod? s_httpPatch; + private static HttpMethod HttpPatch => field ??= new HttpMethod("PATCH"); private static Task PatchAsync(this HttpClient client, string? requestUri, HttpContent content, CancellationToken cancellationToken) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs index ea80a37556bb20..110fc6a7ca29ca 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs @@ -94,7 +94,6 @@ private Func< private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private int _maxResponseDrainSize = HttpHandlerDefaults.DefaultMaxResponseDrainSize; - private IDictionary? _properties; // Only create dictionary when required. private volatile bool _operationStarted; private volatile int _disposed; private SafeWinHttpHandle? _sessionHandle; @@ -575,7 +574,7 @@ public bool EnableMultipleHttp2Connections } } - public IDictionary Properties => _properties ??= new Dictionary(); + public IDictionary Properties => field ??= new Dictionary(); #endregion protected override void Dispose(bool disposing) diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs index af5fef3c13c30d..a8d7818a323bb6 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs @@ -113,8 +113,7 @@ public bool AllowAutoRedirect public const bool SupportsProxy = false; public const bool SupportsRedirectConfiguration = true; - private Dictionary? _properties; - public IDictionary Properties => _properties ??= new Dictionary(); + public IDictionary Properties => field ??= new Dictionary(); protected internal override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs index 960db9edc0d461..da3b0b2f396b05 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.cs @@ -777,12 +777,11 @@ protected internal override Task SendAsync(HttpRequestMessa } // lazy-load the validator func so it can be trimmed by the ILLinker if it isn't used. - private static Func? s_dangerousAcceptAnyServerCertificateValidator; [UnsupportedOSPlatform("browser")] public static Func DangerousAcceptAnyServerCertificateValidator => - s_dangerousAcceptAnyServerCertificateValidator ?? - Interlocked.CompareExchange(ref s_dangerousAcceptAnyServerCertificateValidator, delegate { return true; }, null) ?? - s_dangerousAcceptAnyServerCertificateValidator; + field ?? + Interlocked.CompareExchange(ref field, delegate { return true; }, null) ?? + field; private void ThrowForModifiedManagedSslOptionsIfStarted() { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs index 481eb0212524f6..00b7861f1112dc 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs @@ -372,12 +372,11 @@ protected internal override Task SendAsync(HttpRequestMessa } // lazy-load the validator func so it can be trimmed by the ILLinker if it isn't used. - private static Func? s_dangerousAcceptAnyServerCertificateValidator; [UnsupportedOSPlatform("browser")] public static Func DangerousAcceptAnyServerCertificateValidator => - s_dangerousAcceptAnyServerCertificateValidator ?? - Interlocked.CompareExchange(ref s_dangerousAcceptAnyServerCertificateValidator, delegate { return true; }, null) ?? - s_dangerousAcceptAnyServerCertificateValidator; + field ?? + Interlocked.CompareExchange(ref field, delegate { return true; }, null) ?? + field; private void ThrowForModifiedManagedSslOptionsIfStarted() { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs index beadbc77f17082..b4006543504d70 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionSettings.cs @@ -149,11 +149,9 @@ public HttpConnectionSettings CloneAndNormalize() public bool EnableMultipleHttp3Connections => _enableMultipleHttp3Connections; - private byte[]? _http3SettingsFrame; - [SupportedOSPlatform("windows")] [SupportedOSPlatform("linux")] [SupportedOSPlatform("macos")] - internal byte[] Http3SettingsFrame => _http3SettingsFrame ??= Http3Connection.BuildSettingsFrame(this); + internal byte[] Http3SettingsFrame => field ??= Http3Connection.BuildSettingsFrame(this); } } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/WasiHttpHandler/WasiHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/WasiHttpHandler/WasiHttpHandler.cs index 1003b63b2dc9d3..e4fd54308d9bfe 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/WasiHttpHandler/WasiHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/WasiHttpHandler/WasiHttpHandler.cs @@ -148,8 +148,7 @@ internal sealed class WasiHttpHandler : HttpMessageHandler public const bool SupportsProxy = false; public const bool SupportsRedirectConfiguration = false; - private Dictionary? _properties; - public IDictionary Properties => _properties ??= new Dictionary(); + public IDictionary Properties => field ??= new Dictionary(); protected internal override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index dcce980482ae01..6e4738a660b999 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -25,7 +25,6 @@ public sealed unsafe partial class HttpListenerRequest private readonly string? _cookedUrlPath; private readonly string? _cookedUrlQuery; private long _contentLength; - private Stream? _requestStream; private string? _httpMethod; private WebHeaderCollection? _webHeaders; private IPEndPoint? _localEndPoint; @@ -206,7 +205,7 @@ public string HttpMethod } } - public Stream InputStream => _requestStream ??= HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; + public Stream InputStream => field ??= HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; public bool IsAuthenticated { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs b/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs index 83dfbb84cf0417..61456f5ea9986a 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs @@ -35,7 +35,6 @@ internal sealed class Base64Stream : DelegatedStream, IEncodableStream ]; private readonly Base64WriteStateInfo _writeState; - private ReadStateInfo? _readState; private readonly Base64Encoder _encoder; //bytes with this value in the decode map are invalid @@ -56,7 +55,7 @@ internal Base64Stream(Base64WriteStateInfo writeStateInfo) : base(new MemoryStre public override bool CanRead => BaseStream.CanRead; public override bool CanWrite => BaseStream.CanWrite; - private ReadStateInfo ReadState => _readState ??= new ReadStateInfo(); + private ReadStateInfo ReadState => field ??= new ReadStateInfo(); internal WriteStateInfoBase WriteState { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs index f45299e71152ed..be70ab7b91a530 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs @@ -23,11 +23,8 @@ internal sealed class Message private MailAddress? _from; private MailAddress? _sender; - private MailAddressCollection? _replyToList; private MailAddress? _replyTo; private MailAddressCollection? _to; - private MailAddressCollection? _cc; - private MailAddressCollection? _bcc; private MimeBasePart? _content; private HeaderCollection? _headers; private HeaderCollection? _envelopeHeaders; @@ -118,13 +115,13 @@ internal MailAddress? ReplyTo } } - internal MailAddressCollection ReplyToList => _replyToList ??= new MailAddressCollection(); + internal MailAddressCollection ReplyToList => field ??= new MailAddressCollection(); internal MailAddressCollection To => _to ??= new MailAddressCollection(); - internal MailAddressCollection Bcc => _bcc ??= new MailAddressCollection(); + internal MailAddressCollection Bcc => field ??= new MailAddressCollection(); - internal MailAddressCollection CC => _cc ??= new MailAddressCollection(); + internal MailAddressCollection CC => field ??= new MailAddressCollection(); internal string? Subject diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs index 9f75bad2dfbc3f..6d678d0f5800ac 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs @@ -22,7 +22,6 @@ internal sealed class SmtpTransport private bool _shouldAbort; private bool _enableSsl; - private X509CertificateCollection? _clientCertificates; internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManager.GetModules()) { @@ -68,7 +67,7 @@ internal bool EnableSsl } } - internal X509CertificateCollection ClientCertificates => _clientCertificates ??= new X509CertificateCollection(); + internal X509CertificateCollection ClientCertificates => field ??= new X509CertificateCollection(); internal bool ServerSupportsEai { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/EightBitStream.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/EightBitStream.cs index ae92cf7aeb8def..39f1f673ba37d1 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/EightBitStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/EightBitStream.cs @@ -26,14 +26,12 @@ namespace System.Net.Mime /// internal sealed class EightBitStream : DelegatedStream, IEncodableStream { - private WriteStateInfoBase? _writeState; - // Should we do RFC 2821 Section 4.5.2 encoding of leading dots on a line? // We make this optional because this stream may be used recursively and // the encoding should only be done once. private readonly bool _shouldEncodeLeadingDots; - private WriteStateInfoBase WriteState => _writeState ??= new WriteStateInfoBase(); + private WriteStateInfoBase WriteState => field ??= new WriteStateInfoBase(); /// /// ctor. diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs index e0ffef86590615..4d5a45725a646f 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs @@ -13,7 +13,6 @@ namespace System.Net.Mime { internal sealed class MimeMultiPart : MimeBasePart { - private Collection? _parts; private static int s_boundary; internal MimeMultiPart(MimeMultiPartType type) @@ -39,7 +38,7 @@ private void SetType(MimeMultiPartType type) ContentType.Boundary = GetNextBoundary(); } - internal Collection Parts => _parts ??= new Collection(); + internal Collection Parts => field ??= new Collection(); internal override async Task SendAsync(BaseWriter writer, bool allowUnicode, CancellationToken cancellationToken = default) { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/QEncodedStream.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/QEncodedStream.cs index cafb9b0577e4ff..5b85a1c2c6aceb 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/QEncodedStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/QEncodedStream.cs @@ -39,7 +39,6 @@ internal sealed class QEncodedStream : DelegatedStream, IEncodableStream 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // F ]; - private ReadStateInfo? _readState; private readonly WriteStateInfoBase _writeState; private readonly QEncoder _encoder; @@ -49,7 +48,7 @@ internal QEncodedStream(WriteStateInfoBase wsi) : base(new MemoryStream()) _encoder = new QEncoder(_writeState); } - private ReadStateInfo ReadState => _readState ??= new ReadStateInfo(); + private ReadStateInfo ReadState => field ??= new ReadStateInfo(); internal WriteStateInfoBase WriteState => _writeState; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs index 773e12b430f6c5..cc193d3479f8c5 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs @@ -58,7 +58,6 @@ internal sealed class QuotedPrintableStream : DelegatedStream, IEncodableStream private static ReadOnlySpan HexEncodeMap => "0123456789ABCDEF"u8; private readonly int _lineLength; - private ReadStateInfo? _readState; private WriteStateInfoBase? _writeState; /// @@ -81,7 +80,7 @@ internal QuotedPrintableStream(Stream stream, bool encodeCRLF) : this(stream, En public override bool CanRead => false; public override bool CanWrite => BaseStream.CanWrite; - private ReadStateInfo ReadState => _readState ??= new ReadStateInfo(); + private ReadStateInfo ReadState => field ??= new ReadStateInfo(); internal WriteStateInfoBase WriteState => _writeState ??= new WriteStateInfoBase(1024, null, null, _lineLength); diff --git a/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs b/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs index 5cd541638b23b0..6d585c91042bcb 100644 --- a/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs +++ b/src/libraries/System.Net.Mail/tests/Functional/LoopbackSmtpServer.cs @@ -333,8 +333,7 @@ public class ParsedMailMessage public string Cc => GetHeader("Cc"); public string Subject => GetHeader("Subject"); - private ContentType _contentType; - public ContentType ContentType => _contentType ??= new ContentType(GetHeader("Content-Type")); + public ContentType ContentType => field ??= new ContentType(GetHeader("Content-Type")); private ParsedMailMessage(Dictionary headers, string body, string rawBody, List attachments) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 7694b7007fdaac..f470879e993e41 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -200,7 +200,6 @@ public sealed class FtpWebRequest : WebRequest private bool _passive = true; private bool _binary = true; private string? _connectionGroupName; - private ServicePoint? _servicePoint; private bool _async; private bool _aborted; @@ -216,7 +215,6 @@ public sealed class FtpWebRequest : WebRequest private Stream? _stream; private RequestStage _requestStage; private bool _onceFailed; - private WebHeaderCollection? _ftpRequestHeaders; private FtpWebResponse? _ftpWebResponse; private int _readWriteTimeout = 5 * 60 * 1000; // 5 minutes. @@ -472,7 +470,7 @@ public override string? ConnectionGroupName } } - public ServicePoint ServicePoint => _servicePoint ??= ServicePointManager.FindServicePoint(_uri); + public ServicePoint ServicePoint => field ??= ServicePointManager.FindServicePoint(_uri); internal bool Aborted { @@ -1560,8 +1558,8 @@ public bool EnableSsl public override WebHeaderCollection Headers { - get => _ftpRequestHeaders ??= new WebHeaderCollection(); - set => _ftpRequestHeaders = value; + get => field ??= new WebHeaderCollection(); + set => field = value; } // NOT SUPPORTED method diff --git a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs index adb5537fd6f5b1..f8c6c440170026 100644 --- a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs +++ b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs @@ -27,8 +27,6 @@ public class WebHeaderCollection : NameValueCollection, ISerializable private WebHeaderCollectionType _type; private NameValueCollection? _innerCollection; - private static HeaderInfoTable? _headerInfo; - [Obsolete(Obsoletions.LegacyFormatterImplMessage, DiagnosticId = Obsoletions.LegacyFormatterImplDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] [EditorBrowsable(EditorBrowsableState.Never)] protected WebHeaderCollection(SerializationInfo serializationInfo, StreamingContext streamingContext) @@ -48,7 +46,7 @@ private bool AllowHttpRequestHeader } } - private static HeaderInfoTable HeaderInfo => _headerInfo ??= new HeaderInfoTable(); + private static HeaderInfoTable HeaderInfo => field ??= new HeaderInfoTable(); private NameValueCollection InnerCollection => _innerCollection ??= new NameValueCollection(ApproxHighAvgNumHeaders, StringComparer.OrdinalIgnoreCase); diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/ClientWebSocketOptions.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/ClientWebSocketOptions.cs index aa8164d1099c29..0628b5df9decb7 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/ClientWebSocketOptions.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/BrowserWebSockets/ClientWebSocketOptions.cs @@ -12,7 +12,6 @@ namespace System.Net.WebSockets public sealed class ClientWebSocketOptions { private bool _isReadOnly; // After ConnectAsync is called the options cannot be modified. - private List? _requestedSubProtocols; internal ClientWebSocketOptions() { } @@ -113,7 +112,7 @@ public void AddSubProtocol(string subProtocol) subprotocols.Add(subProtocol); } - internal List RequestedSubProtocols => _requestedSubProtocols ??= new List(); + internal List RequestedSubProtocols => field ??= new List(); [UnsupportedOSPlatform("browser")] public TimeSpan KeepAliveInterval diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs index 7bc3ef949e9114..e52739208f392c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.cs @@ -658,8 +658,7 @@ private static CultureData CreateCultureWithInvariantData() /// Build our invariant information /// We need an invariant instance, which we build hard-coded /// - internal static CultureData Invariant => s_Invariant ??= CreateCultureWithInvariantData(); - private static CultureData? s_Invariant; + internal static CultureData Invariant => field ??= CreateCultureWithInvariantData(); // Cache of cultures we've already looked up private static volatile Dictionary? s_cachedCultures; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs index 547fbc212b0a36..4c721e939b447b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/DateTimeFormatInfo.cs @@ -57,15 +57,9 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable // The culture name used to create this DTFI. private string? _name; - // The language name of the culture used to create this DTFI. - private string? _langName; - // CompareInfo usually used by the parser. private CompareInfo? _compareInfo; - // Culture matches current DTFI. mainly used for string comparisons during parsing. - private CultureInfo? _cultureInfo; - private string? amDesignator; private string? pmDesignator; @@ -141,8 +135,6 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable private string[]? m_abbrevEraNames; private string[]? m_abbrevEnglishEraNames; - private CalendarId[]? optionalCalendars; - private const int DEFAULT_ALL_DATETIMES_SIZE = 132; // CultureInfo updates this @@ -155,9 +147,11 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable private string CultureName => _name ??= _cultureData.CultureName; - private CultureInfo Culture => _cultureInfo ??= CultureInfo.GetCultureInfo(CultureName); + // Culture matches current DTFI. mainly used for string comparisons during parsing. + private CultureInfo Culture => field ??= CultureInfo.GetCultureInfo(CultureName); - private string LanguageName => _langName ??= _cultureData.TwoLetterISOLanguageName; + // The language name of the culture used to create this DTFI. + private string LanguageName => field ??= _cultureData.TwoLetterISOLanguageName; /// /// Create an array of string which contains the abbreviated day names. @@ -465,7 +459,7 @@ public Calendar Calendar } } - private CalendarId[] OptionalCalendars => optionalCalendars ??= _cultureData.CalendarIds; + private CalendarId[] OptionalCalendars => field ??= _cultureData.CalendarIds; /// /// Get the era value by parsing the name of the era. diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs index 8921b87b945361..7e41139b4bf6c5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/NumberFormatInfo.cs @@ -39,7 +39,6 @@ namespace System.Globalization /// public sealed class NumberFormatInfo : IFormatProvider, ICloneable { - private static NumberFormatInfo? s_invariantInfo; internal static readonly string[] s_asciiDigits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; internal static readonly int[] s_intArrayWithElement3 = [3]; @@ -204,7 +203,7 @@ private void VerifyWritable() /// supported and constant irrespective of the current culture. /// Used by FromString methods. /// - public static NumberFormatInfo InvariantInfo => s_invariantInfo ??= + public static NumberFormatInfo InvariantInfo => field ??= // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. CultureInfo.InvariantCulture.NumberFormat; diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs index ef7490d413d49f..f95e54ba338d59 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -26,7 +26,6 @@ private enum Tristate : byte True = 2 } - private string? _listSeparator; private bool _isReadOnly; private readonly string _cultureName; @@ -124,13 +123,13 @@ internal void SetReadOnlyState(bool readOnly) /// public string ListSeparator { - get => _listSeparator ??= _cultureData.ListSeparator; + get => field ??= _cultureData.ListSeparator; set { ArgumentNullException.ThrowIfNull(value); VerifyWritable(); - _listSeparator = value; + field = value; } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs index 46461a0d59bddd..e7c4e948d6c3ce 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/File.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/File.cs @@ -20,10 +20,9 @@ namespace System.IO public static partial class File { private const int ChunkSize = 8192; - private static Encoding? s_UTF8NoBOM; // UTF-8 without BOM and with error detection. Same as the default encoding for StreamWriter. - private static Encoding UTF8NoBOM => s_UTF8NoBOM ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + private static Encoding UTF8NoBOM => field ??= new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); internal const int DefaultBufferSize = 4096; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs index 8fc4bb83cd086b..478d95fd347ac4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/StringWriter.cs @@ -12,8 +12,6 @@ namespace System.IO // the resulting sequence of characters to be presented as a string. public class StringWriter : TextWriter { - private static UnicodeEncoding? s_encoding; - private readonly StringBuilder _sb; private bool _isOpen; @@ -57,7 +55,7 @@ protected override void Dispose(bool disposing) } - public override Encoding Encoding => s_encoding ??= new UnicodeEncoding(false, false); + public override Encoding Encoding => field ??= new UnicodeEncoding(false, false); // Returns the underlying StringBuilder. This is either the StringBuilder // that was passed to the constructor, or the StringBuilder that was diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs index de95ea49016867..646772a3db0a9c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyName.cs @@ -376,7 +376,6 @@ internal static void PercentEncodeByte(byte ch, ref ValueStringBuilder vsb) HexConverter.ToCharsBuffer(ch, vsb.AppendSpan(2), 0, HexConverter.Casing.Upper); } - [field: AllowNull] private static SearchValues UnreservedReserved => field ??= SearchValues.Create("!#$&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz~"); private const int StackallocThreshold = 512; diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs index 02ec3a17b469ae..56681e2af33ae9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs @@ -18,7 +18,6 @@ internal sealed partial class TypeBuilderInstantiation : TypeInfo private Type _genericType; private Type[] _typeArguments; #endregion - private string? _strFullQualName; internal Hashtable _hashtable; @@ -104,7 +103,7 @@ public override Type MakeArrayType(int rank) public override Assembly Assembly => _genericType.Assembly; public override RuntimeTypeHandle TypeHandle => throw new NotSupportedException(); - public override string? FullName => _strFullQualName ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); + public override string? FullName => field ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); public override string? Namespace => _genericType.Namespace; public override string? AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern", diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.Unix.cs index 58e778f1c19585..6ac48537ad816f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/RuntimeInformation.Unix.cs @@ -7,10 +7,9 @@ namespace System.Runtime.InteropServices { public static partial class RuntimeInformation { - private static string? s_osDescription; private static volatile int s_osArchPlusOne; - public static string OSDescription => s_osDescription ??= + public static string OSDescription => field ??= #if TARGET_ANDROID $"Android (API level {Environment.OSVersion.Version.Major})"; #elif TARGET_OSX diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs index 1e96a5905b29e2..12d107a8459f63 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs @@ -61,8 +61,6 @@ public class Task : Task /// A cached task for default(TResult). internal static readonly Task s_defaultResultTask = TaskCache.CreateCacheableTask(default); - private static TaskFactory? s_Factory; - // The value itself, if set. internal TResult? m_result; @@ -474,9 +472,9 @@ internal TResult GetResultCore(bool waitCompletionNotification) /// the default constructor on the factory type. /// public static new TaskFactory Factory => - Volatile.Read(ref s_Factory) ?? - Interlocked.CompareExchange(ref s_Factory, new TaskFactory(), null) ?? - s_Factory; + Volatile.Read(ref field) ?? + Interlocked.CompareExchange(ref field, new(), null) ?? + field; /// /// Evaluates the value selector of the Task which is passed in as an object and stores the result. diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index 7efaed70149168..52bf4ef524b866 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -724,11 +724,9 @@ public override int GetHashCode() public static Type? ReflectionOnlyGetType(string typeName, bool throwIfNotFound, bool ignoreCase) => throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); public static Binder DefaultBinder => - s_defaultBinder ?? - Interlocked.CompareExchange(ref s_defaultBinder, new DefaultBinder(), null) ?? - s_defaultBinder; - - private static Binder? s_defaultBinder; + field ?? + Interlocked.CompareExchange(ref field, new DefaultBinder(), null) ?? + field; public static readonly char Delimiter = '.'; public static readonly Type[] EmptyTypes = Array.Empty(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs index f76e4f0eebd14e..5c334f24e708a8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs @@ -586,8 +586,6 @@ internal bool RequiresMemberAccessForWrite(SecurityException? securityException) private sealed class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { - private static Type[]? s_serInfoCtorArgs; - private ClassDataContract? _baseContract; private List? _members; private MethodInfo? _onSerializing, _onSerialized; @@ -1275,7 +1273,7 @@ internal override DataContractDictionary? KnownDataContracts internal XmlDictionaryString?[]? ChildElementNamespaces { get; set; } - private static Type[] SerInfoCtorArgs => s_serInfoCtorArgs ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; + private static Type[] SerInfoCtorArgs => field ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; internal readonly struct Member { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 8366258cc00d8b..3c49ba5a0d061b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -94,8 +94,7 @@ internal static MethodInfo GetInvokeMethod(Type delegateType) private Type _delegateType = null!; // initialized in BeginMethod - private static Module? s_serializationModule; - private static Module SerializationModule => s_serializationModule ??= typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false + private static Module SerializationModule => field ??= typeof(CodeGenerator).Module; // could to be replaced by different dll that has SkipVerification set to false private DynamicMethod _dynamicMethod = null!; // initialized in BeginMethod diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index 371dd171255648..3b8c59d2ca3117 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -316,7 +316,6 @@ internal class DataContractCriticalHelper [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] private readonly Type _underlyingType; - private Type? _originalUnderlyingType; private bool _isValueType; private GenericInfo? _genericInfo; private XmlQualifiedName _xmlName = null!; // XmlName is always set in concrete ctors set except for the "invalid" CollectionDataContract @@ -949,7 +948,7 @@ internal DataContractCriticalHelper( [DynamicallyAccessedMembers(ClassDataContract.DataContractPreserveMemberTypes)] internal Type UnderlyingType => _underlyingType; - internal Type OriginalUnderlyingType => _originalUnderlyingType ??= GetDataContractOriginalType(_underlyingType); + internal Type OriginalUnderlyingType => field ??= GetDataContractOriginalType(_underlyingType); internal virtual bool IsBuiltInDataContract => false; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 58176b6dc52ccd..1a1819be2bcc64 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -18,7 +18,6 @@ public sealed class DataContractSet private Dictionary? _processedContracts; private readonly ISerializationSurrogateProvider? _surrogateProvider; private readonly ISerializationSurrogateProvider2? _extendedSurrogateProvider; - private Hashtable? _surrogateData; private DataContractDictionary? _knownTypesForObject; private readonly List? _referencedTypes; private readonly List? _referencedCollectionTypes; @@ -61,7 +60,7 @@ public DataContractSet(DataContractSet dataContractSet) public Dictionary ProcessedContracts => _processedContracts ??= new Dictionary(); - public Hashtable SurrogateData => _surrogateData ??= new Hashtable(); + public Hashtable SurrogateData => field ??= new Hashtable(); public DataContractDictionary? KnownTypesForObject { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs index 5c07f7d8265e1e..e655439ed92fb1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs @@ -88,11 +88,8 @@ internal DataMember? ConflictingMember set => _helper.ConflictingMember = value; } - private FastInvokerBuilder.Getter? _getter; - internal FastInvokerBuilder.Getter Getter => _getter ??= FastInvokerBuilder.CreateGetter(MemberInfo); - - private FastInvokerBuilder.Setter? _setter; - internal FastInvokerBuilder.Setter Setter => _setter ??= FastInvokerBuilder.CreateSetter(MemberInfo); + internal FastInvokerBuilder.Getter Getter => field ??= FastInvokerBuilder.CreateGetter(MemberInfo); + internal FastInvokerBuilder.Setter Setter => field ??= FastInvokerBuilder.CreateSetter(MemberInfo); private sealed class CriticalHelper { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs index 8034f326ea09ec..9ab6f35c32bee8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs @@ -15,8 +15,6 @@ namespace System.Runtime.Serialization /// public class ExportOptions { - private Collection? _knownTypes; - /// /// Gets or sets a serialization surrogate provider. /// @@ -25,6 +23,6 @@ public class ExportOptions /// /// Gets the collection of types that may be encountered during serialization or deserialization. /// - public Collection KnownTypes => _knownTypes ??= new Collection(); + public Collection KnownTypes => field ??= new Collection(); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs index 65e88a4ac221b4..060e7f9964be83 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs @@ -23,299 +23,86 @@ internal static partial class Globals /// internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; - private static XmlQualifiedName? s_idQualifiedName; - internal static XmlQualifiedName IdQualifiedName => - s_idQualifiedName ??= new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); - - private static XmlQualifiedName? s_refQualifiedName; - internal static XmlQualifiedName RefQualifiedName => - s_refQualifiedName ??= new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); - - private static Type? s_typeOfObject; - internal static Type TypeOfObject => - s_typeOfObject ??= typeof(object); - - private static Type? s_typeOfValueType; - internal static Type TypeOfValueType => - s_typeOfValueType ??= typeof(ValueType); - - private static Type? s_typeOfArray; - internal static Type TypeOfArray => - s_typeOfArray ??= typeof(Array); - - private static Type? s_typeOfString; - internal static Type TypeOfString => - s_typeOfString ??= typeof(string); - - private static Type? s_typeOfInt; - internal static Type TypeOfInt => - s_typeOfInt ??= typeof(int); - - private static Type? s_typeOfULong; - internal static Type TypeOfULong => - s_typeOfULong ??= typeof(ulong); - - private static Type? s_typeOfVoid; - internal static Type TypeOfVoid => - s_typeOfVoid ??= typeof(void); - - private static Type? s_typeOfByteArray; - internal static Type TypeOfByteArray => - s_typeOfByteArray ??= typeof(byte[]); - - private static Type? s_typeOfTimeSpan; - internal static Type TypeOfTimeSpan => - s_typeOfTimeSpan ??= typeof(TimeSpan); - - private static Type? s_typeOfGuid; - internal static Type TypeOfGuid => - s_typeOfGuid ??= typeof(Guid); - - private static Type? s_typeOfDateTimeOffset; - internal static Type TypeOfDateTimeOffset => - s_typeOfDateTimeOffset ??= typeof(DateTimeOffset); - - private static Type? s_typeOfDateTimeOffsetAdapter; - internal static Type TypeOfDateTimeOffsetAdapter => - s_typeOfDateTimeOffsetAdapter ??= typeof(DateTimeOffsetAdapter); - - private static Type? s_typeOfMemoryStream; - internal static Type TypeOfMemoryStream => - s_typeOfMemoryStream ??= typeof(MemoryStream); - - private static Type? s_typeOfMemoryStreamAdapter; - internal static Type TypeOfMemoryStreamAdapter => - s_typeOfMemoryStreamAdapter ??= typeof(MemoryStreamAdapter); - - private static Type? s_typeOfUri; - internal static Type TypeOfUri => - s_typeOfUri ??= typeof(Uri); - - private static Type? s_typeOfTypeEnumerable; - internal static Type TypeOfTypeEnumerable => - s_typeOfTypeEnumerable ??= typeof(IEnumerable); - - private static Type? s_typeOfStreamingContext; - internal static Type TypeOfStreamingContext => - s_typeOfStreamingContext ??= typeof(StreamingContext); - - private static Type? s_typeOfISerializable; - internal static Type TypeOfISerializable => - s_typeOfISerializable ??= typeof(ISerializable); - - private static Type? s_typeOfIDeserializationCallback; - internal static Type TypeOfIDeserializationCallback => - s_typeOfIDeserializationCallback ??= typeof(IDeserializationCallback); - + internal static XmlQualifiedName IdQualifiedName => field ??= new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName RefQualifiedName => field ??= new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); + internal static Type TypeOfObject => field ??= typeof(object); + internal static Type TypeOfValueType => field ??= typeof(ValueType); + internal static Type TypeOfArray => field ??= typeof(Array); + internal static Type TypeOfString => field ??= typeof(string); + internal static Type TypeOfInt => field ??= typeof(int); + internal static Type TypeOfULong => field ??= typeof(ulong); + internal static Type TypeOfVoid => field ??= typeof(void); + internal static Type TypeOfByteArray => field ??= typeof(byte[]); + internal static Type TypeOfTimeSpan => field ??= typeof(TimeSpan); + internal static Type TypeOfGuid => field ??= typeof(Guid); + internal static Type TypeOfDateTimeOffset => field ??= typeof(DateTimeOffset); + internal static Type TypeOfDateTimeOffsetAdapter => field ??= typeof(DateTimeOffsetAdapter); + internal static Type TypeOfMemoryStream => field ??= typeof(MemoryStream); + internal static Type TypeOfMemoryStreamAdapter => field ??= typeof(MemoryStreamAdapter); + internal static Type TypeOfUri => field ??= typeof(Uri); + internal static Type TypeOfTypeEnumerable => field ??= typeof(IEnumerable); + internal static Type TypeOfStreamingContext => field ??= typeof(StreamingContext); + internal static Type TypeOfISerializable => field ??= typeof(ISerializable); + internal static Type TypeOfIDeserializationCallback => field ??= typeof(IDeserializationCallback); #pragma warning disable SYSLIB0050 // IObjectReference is obsolete - private static Type? s_typeOfIObjectReference; - internal static Type TypeOfIObjectReference => - s_typeOfIObjectReference ??= typeof(IObjectReference); + internal static Type TypeOfIObjectReference => field ??= typeof(IObjectReference); #pragma warning restore SYSLIB0050 - - private static Type? s_typeOfXmlFormatClassWriterDelegate; - internal static Type TypeOfXmlFormatClassWriterDelegate => - s_typeOfXmlFormatClassWriterDelegate ??= typeof(XmlFormatClassWriterDelegate); - - private static Type? s_typeOfXmlFormatCollectionWriterDelegate; - internal static Type TypeOfXmlFormatCollectionWriterDelegate => - s_typeOfXmlFormatCollectionWriterDelegate ??= typeof(XmlFormatCollectionWriterDelegate); - - private static Type? s_typeOfXmlFormatClassReaderDelegate; - internal static Type TypeOfXmlFormatClassReaderDelegate => - s_typeOfXmlFormatClassReaderDelegate ??= typeof(XmlFormatClassReaderDelegate); - - private static Type? s_typeOfXmlFormatCollectionReaderDelegate; - internal static Type TypeOfXmlFormatCollectionReaderDelegate => - s_typeOfXmlFormatCollectionReaderDelegate ??= typeof(XmlFormatCollectionReaderDelegate); - - private static Type? s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; - internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate => - s_typeOfXmlFormatGetOnlyCollectionReaderDelegate ??= typeof(XmlFormatGetOnlyCollectionReaderDelegate); - - private static Type? s_typeOfKnownTypeAttribute; - internal static Type TypeOfKnownTypeAttribute => - s_typeOfKnownTypeAttribute ??= typeof(KnownTypeAttribute); - - private static Type? s_typeOfDataContractAttribute; - internal static Type TypeOfDataContractAttribute => - s_typeOfDataContractAttribute ??= typeof(DataContractAttribute); - - private static Type? s_typeOfDataMemberAttribute; - internal static Type TypeOfDataMemberAttribute => - s_typeOfDataMemberAttribute ??= typeof(DataMemberAttribute); - - private static Type? s_typeOfEnumMemberAttribute; - internal static Type TypeOfEnumMemberAttribute => - s_typeOfEnumMemberAttribute ??= typeof(EnumMemberAttribute); - - private static Type? s_typeOfCollectionDataContractAttribute; - internal static Type TypeOfCollectionDataContractAttribute => - s_typeOfCollectionDataContractAttribute ??= typeof(CollectionDataContractAttribute); - - private static Type? s_typeOfOptionalFieldAttribute; - internal static Type TypeOfOptionalFieldAttribute => - s_typeOfOptionalFieldAttribute ??= typeof(OptionalFieldAttribute); - - private static Type? s_typeOfObjectArray; - internal static Type TypeOfObjectArray => - s_typeOfObjectArray ??= typeof(object[]); - - private static Type? s_typeOfOnSerializingAttribute; - internal static Type TypeOfOnSerializingAttribute => - s_typeOfOnSerializingAttribute ??= typeof(OnSerializingAttribute); - - private static Type? s_typeOfOnSerializedAttribute; - internal static Type TypeOfOnSerializedAttribute => - s_typeOfOnSerializedAttribute ??= typeof(OnSerializedAttribute); - - private static Type? s_typeOfOnDeserializingAttribute; - internal static Type TypeOfOnDeserializingAttribute => - s_typeOfOnDeserializingAttribute ??= typeof(OnDeserializingAttribute); - - private static Type? s_typeOfOnDeserializedAttribute; - internal static Type TypeOfOnDeserializedAttribute => - s_typeOfOnDeserializedAttribute ??= typeof(OnDeserializedAttribute); - - private static Type? s_typeOfFlagsAttribute; - internal static Type TypeOfFlagsAttribute => - s_typeOfFlagsAttribute ??= typeof(FlagsAttribute); - - private static Type? s_typeOfIXmlSerializable; - internal static Type TypeOfIXmlSerializable => - s_typeOfIXmlSerializable ??= typeof(IXmlSerializable); - - private static Type? s_typeOfXmlSchemaProviderAttribute; - internal static Type TypeOfXmlSchemaProviderAttribute => - s_typeOfXmlSchemaProviderAttribute ??= typeof(XmlSchemaProviderAttribute); - - private static Type? s_typeOfXmlRootAttribute; - internal static Type TypeOfXmlRootAttribute => - s_typeOfXmlRootAttribute ??= typeof(XmlRootAttribute); - - private static Type? s_typeOfXmlQualifiedName; - internal static Type TypeOfXmlQualifiedName => - s_typeOfXmlQualifiedName ??= typeof(XmlQualifiedName); - - private static Type? s_typeOfXmlSchemaType; - internal static Type TypeOfXmlSchemaType => - s_typeOfXmlSchemaType ??= typeof(XmlSchemaType); - - private static Type? s_typeOfIExtensibleDataObject; - internal static Type TypeOfIExtensibleDataObject => - s_typeOfIExtensibleDataObject ??= typeof(IExtensibleDataObject); - - private static Type? s_typeOfExtensionDataObject; - internal static Type TypeOfExtensionDataObject => - s_typeOfExtensionDataObject ??= typeof(ExtensionDataObject); - - private static Type? s_typeOfISerializableDataNode; - internal static Type TypeOfISerializableDataNode => - s_typeOfISerializableDataNode ??= typeof(ISerializableDataNode); - - private static Type? s_typeOfClassDataNode; - internal static Type TypeOfClassDataNode => - s_typeOfClassDataNode ??= typeof(ClassDataNode); - - private static Type? s_typeOfCollectionDataNode; - internal static Type TypeOfCollectionDataNode => - s_typeOfCollectionDataNode ??= typeof(CollectionDataNode); - - private static Type? s_typeOfXmlDataNode; - internal static Type TypeOfXmlDataNode => - s_typeOfXmlDataNode ??= typeof(XmlDataNode); - - private static Type? s_typeOfNullable; - internal static Type TypeOfNullable => - s_typeOfNullable ??= typeof(Nullable<>); - - private static Type? s_typeOfReflectionPointer; - internal static Type TypeOfReflectionPointer => - s_typeOfReflectionPointer ??= typeof(System.Reflection.Pointer); - - private static Type? s_typeOfIDictionaryGeneric; - internal static Type TypeOfIDictionaryGeneric => - s_typeOfIDictionaryGeneric ??= typeof(IDictionary<,>); - - private static Type? s_typeOfIDictionary; - internal static Type TypeOfIDictionary => - s_typeOfIDictionary ??= typeof(IDictionary); - - private static Type? s_typeOfIListGeneric; - internal static Type TypeOfIListGeneric => - s_typeOfIListGeneric ??= typeof(IList<>); - - private static Type? s_typeOfIList; - internal static Type TypeOfIList => - s_typeOfIList ??= typeof(IList); - - private static Type? s_typeOfICollectionGeneric; - internal static Type TypeOfICollectionGeneric => - s_typeOfICollectionGeneric ??= typeof(ICollection<>); - - private static Type? s_typeOfICollection; - internal static Type TypeOfICollection => - s_typeOfICollection ??= typeof(ICollection); - - private static Type? s_typeOfIEnumerableGeneric; - internal static Type TypeOfIEnumerableGeneric => - s_typeOfIEnumerableGeneric ??= typeof(IEnumerable<>); - - private static Type? s_typeOfIEnumerable; - internal static Type TypeOfIEnumerable => - s_typeOfIEnumerable ??= typeof(IEnumerable); - - private static Type? s_typeOfIEnumeratorGeneric; - internal static Type TypeOfIEnumeratorGeneric => - s_typeOfIEnumeratorGeneric ??= typeof(IEnumerator<>); - - private static Type? s_typeOfIEnumerator; - internal static Type TypeOfIEnumerator => - s_typeOfIEnumerator ??= typeof(IEnumerator); - - private static Type? s_typeOfKeyValuePair; - internal static Type TypeOfKeyValuePair => - s_typeOfKeyValuePair ??= typeof(KeyValuePair<,>); - - private static Type? s_typeOfKeyValue; - internal static Type TypeOfKeyValue => - s_typeOfKeyValue ??= typeof(KeyValue<,>); - - private static Type? s_typeOfIDictionaryEnumerator; - internal static Type TypeOfIDictionaryEnumerator => - s_typeOfIDictionaryEnumerator ??= typeof(IDictionaryEnumerator); - - private static Type? s_typeOfDictionaryEnumerator; - internal static Type TypeOfDictionaryEnumerator => - s_typeOfDictionaryEnumerator ??= typeof(CollectionDataContract.DictionaryEnumerator); - - private static Type? s_typeOfGenericDictionaryEnumerator; - internal static Type TypeOfGenericDictionaryEnumerator => - s_typeOfGenericDictionaryEnumerator ??= typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); - - private static Type? s_typeOfDictionaryGeneric; - internal static Type TypeOfDictionaryGeneric => - s_typeOfDictionaryGeneric ??= typeof(Dictionary<,>); - - private static Type? s_typeOfHashtable; + internal static Type TypeOfXmlFormatClassWriterDelegate => field ??= typeof(XmlFormatClassWriterDelegate); + internal static Type TypeOfXmlFormatCollectionWriterDelegate => field ??= typeof(XmlFormatCollectionWriterDelegate); + internal static Type TypeOfXmlFormatClassReaderDelegate => field ??= typeof(XmlFormatClassReaderDelegate); + internal static Type TypeOfXmlFormatCollectionReaderDelegate => field ??= typeof(XmlFormatCollectionReaderDelegate); + internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate => field ??= typeof(XmlFormatGetOnlyCollectionReaderDelegate); + internal static Type TypeOfKnownTypeAttribute => field ??= typeof(KnownTypeAttribute); + internal static Type TypeOfDataContractAttribute => field ??= typeof(DataContractAttribute); + internal static Type TypeOfDataMemberAttribute => field ??= typeof(DataMemberAttribute); + internal static Type TypeOfEnumMemberAttribute => field ??= typeof(EnumMemberAttribute); + internal static Type TypeOfCollectionDataContractAttribute => field ??= typeof(CollectionDataContractAttribute); + internal static Type TypeOfOptionalFieldAttribute => field ??= typeof(OptionalFieldAttribute); + internal static Type TypeOfObjectArray => field ??= typeof(object[]); + internal static Type TypeOfOnSerializingAttribute => field ??= typeof(OnSerializingAttribute); + internal static Type TypeOfOnSerializedAttribute => field ??= typeof(OnSerializedAttribute); + internal static Type TypeOfOnDeserializingAttribute => field ??= typeof(OnDeserializingAttribute); + internal static Type TypeOfOnDeserializedAttribute => field ??= typeof(OnDeserializedAttribute); + internal static Type TypeOfFlagsAttribute => field ??= typeof(FlagsAttribute); + internal static Type TypeOfIXmlSerializable => field ??= typeof(IXmlSerializable); + internal static Type TypeOfXmlSchemaProviderAttribute => field ??= typeof(XmlSchemaProviderAttribute); + internal static Type TypeOfXmlRootAttribute => field ??= typeof(XmlRootAttribute); + internal static Type TypeOfXmlQualifiedName => field ??= typeof(XmlQualifiedName); + internal static Type TypeOfXmlSchemaType => field ??= typeof(XmlSchemaType); + internal static Type TypeOfIExtensibleDataObject => field ??= typeof(IExtensibleDataObject); + internal static Type TypeOfExtensionDataObject => field ??= typeof(ExtensionDataObject); + internal static Type TypeOfISerializableDataNode => field ??= typeof(ISerializableDataNode); + internal static Type TypeOfClassDataNode => field ??= typeof(ClassDataNode); + internal static Type TypeOfCollectionDataNode => field ??= typeof(CollectionDataNode); + internal static Type TypeOfXmlDataNode => field ??= typeof(XmlDataNode); + internal static Type TypeOfNullable => field ??= typeof(Nullable<>); + internal static Type TypeOfReflectionPointer => field ??= typeof(System.Reflection.Pointer); + internal static Type TypeOfIDictionaryGeneric => field ??= typeof(IDictionary<,>); + internal static Type TypeOfIDictionary => field ??= typeof(IDictionary); + internal static Type TypeOfIListGeneric => field ??= typeof(IList<>); + internal static Type TypeOfIList => field ??= typeof(IList); + internal static Type TypeOfICollectionGeneric => field ??= typeof(ICollection<>); + internal static Type TypeOfICollection => field ??= typeof(ICollection); + internal static Type TypeOfIEnumerableGeneric => field ??= typeof(IEnumerable<>); + internal static Type TypeOfIEnumerable => field ??= typeof(IEnumerable); + internal static Type TypeOfIEnumeratorGeneric => field ??= typeof(IEnumerator<>); + internal static Type TypeOfIEnumerator => field ??= typeof(IEnumerator); + internal static Type TypeOfKeyValuePair => field ??= typeof(KeyValuePair<,>); + internal static Type TypeOfKeyValue => field ??= typeof(KeyValue<,>); + internal static Type TypeOfIDictionaryEnumerator => field ??= typeof(IDictionaryEnumerator); + internal static Type TypeOfDictionaryEnumerator => field ??= typeof(CollectionDataContract.DictionaryEnumerator); + internal static Type TypeOfGenericDictionaryEnumerator => field ??= typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); + internal static Type TypeOfDictionaryGeneric => field ??= typeof(Dictionary<,>); internal static Type TypeOfHashtable { [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - get => s_typeOfHashtable ??= TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); + get => field ??= TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); } - private static Type? s_typeOfXmlElement; - internal static Type TypeOfXmlElement => - s_typeOfXmlElement ??= typeof(XmlElement); - - private static Type? s_typeOfXmlNodeArray; - internal static Type TypeOfXmlNodeArray => - s_typeOfXmlNodeArray ??= typeof(XmlNode[]); - - private static Type? s_typeOfDBNull; - internal static Type TypeOfDBNull => - s_typeOfDBNull ??= typeof(DBNull); + internal static Type TypeOfXmlElement => field ??= typeof(XmlElement); + internal static Type TypeOfXmlNodeArray => field ??= typeof(XmlNode[]); + internal static Type TypeOfDBNull => field ??= typeof(DBNull); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.NonPublicFields)] private static Type? s_typeOfSchemaDefinedType; @@ -329,13 +116,8 @@ internal static Type TypeOfHashtable internal static Type TypeOfSchemaDefinedEnum => s_typeOfSchemaDefinedEnum ??= typeof(SchemaDefinedEnum); - private static MemberInfo? s_schemaMemberInfoPlaceholder; - internal static MemberInfo SchemaMemberInfoPlaceholder => - s_schemaMemberInfoPlaceholder ??= TypeOfSchemaDefinedType.GetField(nameof(SchemaDefinedType._xmlName), BindingFlags.NonPublic | BindingFlags.Instance)!; - - private static Uri? s_dataContractXsdBaseNamespaceUri; - internal static Uri DataContractXsdBaseNamespaceUri => - s_dataContractXsdBaseNamespaceUri ??= new Uri(DataContractXsdBaseNamespace); + internal static MemberInfo SchemaMemberInfoPlaceholder => field ??= TypeOfSchemaDefinedType.GetField(nameof(SchemaDefinedType._xmlName), BindingFlags.NonPublic | BindingFlags.Instance)!; + internal static Uri DataContractXsdBaseNamespaceUri => field ??= new Uri(DataContractXsdBaseNamespace); public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs index ff78bb15130c66..297cd6929df553 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs @@ -18,10 +18,6 @@ public static class JsonFormatGeneratorStatics private static PropertyInfo? s_collectionItemNameProperty; - private static ConstructorInfo? s_extensionDataObjectCtor; - - private static PropertyInfo? s_extensionDataProperty; - private static MethodInfo? s_getItemContractMethod; private static MethodInfo? s_getJsonDataContractMethod; @@ -54,8 +50,6 @@ public static class JsonFormatGeneratorStatics private static ConstructorInfo? s_serializationExceptionCtor; - private static Type[]? s_serInfoCtorArgs; - private static MethodInfo? s_throwDuplicateMemberExceptionMethod; private static MethodInfo? s_throwMissingRequiredMembersMethod; @@ -113,11 +107,9 @@ public static PropertyInfo CollectionItemNameProperty } } - public static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ?? - (s_extensionDataObjectCtor = - typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, Type.EmptyTypes))!; + public static ConstructorInfo ExtensionDataObjectCtor => field ??= typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, Type.EmptyTypes)!; - public static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??= typeof(IExtensibleDataObject).GetProperty("ExtensionData")!; + public static PropertyInfo ExtensionDataProperty => field ??= typeof(IExtensibleDataObject).GetProperty("ExtensionData")!; public static MethodInfo GetCurrentMethod { @@ -319,7 +311,7 @@ public static ConstructorInfo SerializationExceptionCtor return s_serializationExceptionCtor; } } - public static Type[] SerInfoCtorArgs => s_serInfoCtorArgs ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; + public static Type[] SerInfoCtorArgs => field ??= new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }; public static MethodInfo ThrowDuplicateMemberExceptionMethod { get diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 1c05bf37fde453..3733783c3b3800 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -871,32 +871,15 @@ internal static XmlSchemaAny ISerializableWildcardElement } } - private static XmlQualifiedName? s_anytypeQualifiedName; - internal static XmlQualifiedName AnytypeQualifiedName => s_anytypeQualifiedName ??= new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace); - - private static XmlQualifiedName? s_stringQualifiedName; - internal static XmlQualifiedName StringQualifiedName => s_stringQualifiedName ??= new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace); - - private static XmlQualifiedName? s_defaultEnumBaseTypeName; - internal static XmlQualifiedName DefaultEnumBaseTypeName => s_defaultEnumBaseTypeName ??= new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace); - - private static XmlQualifiedName? s_enumerationValueAnnotationName; - internal static XmlQualifiedName EnumerationValueAnnotationName => s_enumerationValueAnnotationName ??= new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace); - - private static XmlQualifiedName? s_surrogateDataAnnotationName; - internal static XmlQualifiedName SurrogateDataAnnotationName => s_surrogateDataAnnotationName ??= new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace); - - private static XmlQualifiedName? s_defaultValueAnnotation; - internal static XmlQualifiedName DefaultValueAnnotation => s_defaultValueAnnotation ??= new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace); - - private static XmlQualifiedName? s_actualTypeAnnotationName; - internal static XmlQualifiedName ActualTypeAnnotationName => s_actualTypeAnnotationName ??= new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace); - - private static XmlQualifiedName? s_isDictionaryAnnotationName; - internal static XmlQualifiedName IsDictionaryAnnotationName => s_isDictionaryAnnotationName ??= new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace); - - private static XmlQualifiedName? s_isValueTypeName; - internal static XmlQualifiedName IsValueTypeName => s_isValueTypeName ??= new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName AnytypeQualifiedName => field ??= new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace); + internal static XmlQualifiedName StringQualifiedName => field ??= new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace); + internal static XmlQualifiedName DefaultEnumBaseTypeName => field ??= new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace); + internal static XmlQualifiedName EnumerationValueAnnotationName => field ??= new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName SurrogateDataAnnotationName => field ??= new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName DefaultValueAnnotation => field ??= new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName ActualTypeAnnotationName => field ??= new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName IsDictionaryAnnotationName => field ??= new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace); + internal static XmlQualifiedName IsValueTypeName => field ??= new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace); // Property is not stored in a local because XmlSchemaAttribute is mutable. // The schema export process should not expose objects that may be modified later. diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs index 1d18543b4c0946..399e530eaff868 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs @@ -68,11 +68,9 @@ internal static MethodInfo WriteNamespaceDeclMethod } } - private static PropertyInfo? s_extensionDataProperty; - internal static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ??= typeof(IExtensibleDataObject).GetProperty("ExtensionData")!; + internal static PropertyInfo ExtensionDataProperty => field ??= typeof(IExtensibleDataObject).GetProperty("ExtensionData")!; - private static MethodInfo? s_boxPointer; - internal static MethodInfo BoxPointer => s_boxPointer ??= typeof(Pointer).GetMethod("Box")!; + internal static MethodInfo BoxPointer => field ??= typeof(Pointer).GetMethod("Box")!; private static ConstructorInfo? s_dictionaryEnumeratorCtor; internal static ConstructorInfo DictionaryEnumeratorCtor @@ -188,8 +186,7 @@ internal static MethodInfo OnDeserializationMethod } } - private static MethodInfo? s_unboxPointer; - internal static MethodInfo UnboxPointer => s_unboxPointer ??= typeof(Pointer).GetMethod("Unbox")!; + internal static MethodInfo UnboxPointer => field ??= typeof(Pointer).GetMethod("Unbox")!; private static PropertyInfo? s_nodeTypeProperty; internal static PropertyInfo NodeTypeProperty @@ -205,11 +202,9 @@ internal static PropertyInfo NodeTypeProperty } } - private static ConstructorInfo? s_serializationExceptionCtor; - internal static ConstructorInfo SerializationExceptionCtor => s_serializationExceptionCtor ??= typeof(SerializationException).GetConstructor(new Type[] { typeof(string) })!; + internal static ConstructorInfo SerializationExceptionCtor => field ??= typeof(SerializationException).GetConstructor(new Type[] { typeof(string) })!; - private static ConstructorInfo? s_extensionDataObjectCtor; - internal static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ??= typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, Type.EmptyTypes)!; + internal static ConstructorInfo ExtensionDataObjectCtor => field ??= typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, Type.EmptyTypes)!; private static ConstructorInfo? s_hashtableCtor; internal static ConstructorInfo HashtableCtor @@ -912,8 +907,7 @@ internal static FieldInfo MemberNamesField } } - private static MethodInfo? s_extensionDataSetExplicitMethodInfo; - internal static MethodInfo ExtensionDataSetExplicitMethodInfo => s_extensionDataSetExplicitMethodInfo ??= typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod)!; + internal static MethodInfo ExtensionDataSetExplicitMethodInfo => field ??= typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod)!; private static PropertyInfo? s_childElementNamespacesProperty; internal static PropertyInfo ChildElementNamespacesProperty diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index 778191ff35e67e..3dcd6c7886b417 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -471,8 +471,7 @@ internal static string GetTypeInfoError(string errorMessage, Type? type, Excepti } #pragma warning disable SYSLIB0050 // IFormatterConverter is obsolete - private static IFormatterConverter? s_formatterConverter; - internal static IFormatterConverter FormatterConverter => s_formatterConverter ??= new FormatterConverter(); + internal static IFormatterConverter FormatterConverter => field ??= new FormatterConverter(); #pragma warning restore SYSLIB0050 } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index b04258f0da9903..aa67d42b32f239 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -19,17 +19,15 @@ namespace System.Runtime.Serialization internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext { internal Attributes? attributes; - private HybridObjectCache? _deserializedObjects; private XmlSerializableReader? _xmlSerializableReader; - private XmlDocument? _xmlDocument; private Attributes? _attributesInXmlData; private XmlReaderDelegator? _extensionDataReader; private object? _getOnlyCollectionValue; private bool _isGetOnlyCollection; - private HybridObjectCache DeserializedObjects => _deserializedObjects ??= new HybridObjectCache(); + private HybridObjectCache DeserializedObjects => field ??= new HybridObjectCache(); - private XmlDocument Document => _xmlDocument ??= new XmlDocument(); + private XmlDocument Document => field ??= new XmlDocument(); internal override bool IsGetOnlyCollection { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs index 150209bfba79b4..77871d386de520 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs @@ -25,7 +25,6 @@ internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext private ObjectReferenceStack _byValObjectsInScope; private XmlSerializableWriter? _xmlSerializableWriter; private const int depthToCheckCyclicReference = 512; - private ObjectToIdCache? _serializedObjects; private bool _isGetOnlyCollection; private readonly bool _unsafeTypeForwardingEnabled; protected bool serializeReadOnlyTypes; @@ -53,7 +52,7 @@ internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int max _unsafeTypeForwardingEnabled = true; } - protected ObjectToIdCache SerializedObjects => _serializedObjects ??= new ObjectToIdCache(); + protected ObjectToIdCache SerializedObjects => field ??= new ObjectToIdCache(); internal override bool IsGetOnlyCollection { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs index 00d058c678e458..deeab58bd93119 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs @@ -15,12 +15,11 @@ namespace System.Xml { public class XmlDictionary : IXmlDictionary { - private static IXmlDictionary? s_empty; private readonly Dictionary _lookup; private XmlDictionaryString[]? _strings; private int _nextId; - public static IXmlDictionary Empty => s_empty ??= new EmptyDictionary(); + public static IXmlDictionary Empty => field ??= new EmptyDictionary(); public XmlDictionary() { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs index 8d4042a9a719e5..8b3e53de4d5c42 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs @@ -14,9 +14,7 @@ namespace System.Xml { internal abstract class XmlNodeWriter { - private static XmlNodeWriter? s_nullNodeWriter; - - public static XmlNodeWriter Null => s_nullNodeWriter ??= new XmlNullNodeWriter(); + public static XmlNodeWriter Null => field ??= new XmlNullNodeWriter(); public abstract void Flush(); public virtual Task FlushAsync() diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs index 4039b9bdcfc387..5843fc5654019c 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs @@ -28,9 +28,6 @@ namespace System.Xml.Linq /// public abstract class XNode : XObject { - private static XNodeDocumentOrderComparer? s_documentOrderComparer; - private static XNodeEqualityComparer? s_equalityComparer; - internal XNode? next; internal XNode() { } @@ -77,12 +74,12 @@ public XNode? PreviousNode /// /// Gets a comparer that can compare the relative position of two nodes. /// - public static XNodeDocumentOrderComparer DocumentOrderComparer => s_documentOrderComparer ??= new XNodeDocumentOrderComparer(); + public static XNodeDocumentOrderComparer DocumentOrderComparer => field ??= new XNodeDocumentOrderComparer(); /// /// Gets a comparer that can compare two nodes for value equality. /// - public static XNodeEqualityComparer EqualityComparer => s_equalityComparer ??= new XNodeEqualityComparer(); + public static XNodeEqualityComparer EqualityComparer => field ??= new XNodeEqualityComparer(); /// /// Adds the specified content immediately after this node. The diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index a7f9c855edfa00..c53b6a7b25be82 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -74,7 +74,6 @@ private static readonly (string key, int hash)[] s_nameTableSeeds = new[] private readonly XmlImplementation _implementation; private readonly DomNameTable _domNameTable; // hash table of XmlName private XmlLinkedNode? _lastChild; - private XmlNamedNodeMap? _entities; private Hashtable? _htElementIdMap; private Hashtable? _htElementIDAttrDecl; //key: id; object: the ArrayList of the elements that have the same id (connected or disconnected) private SchemaInfo? _schemaInfo; @@ -1090,8 +1089,8 @@ public override bool IsReadOnly internal XmlNamedNodeMap Entities { - get => _entities ??= new XmlNamedNodeMap(this); - set => _entities = value; + get => field ??= new XmlNamedNodeMap(this); + set => field = value; } internal bool IsLoading diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs index fffb34a10f47d4..8bffa0636e8162 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs @@ -14,8 +14,6 @@ public class XmlDocumentType : XmlLinkedNode private readonly string? _systemId; private readonly string? _internalSubset; private bool _namespaces; - private XmlNamedNodeMap? _entities; - private XmlNamedNodeMap? _notations; // parsed DTD private SchemaInfo? _schemaInfo; @@ -76,10 +74,10 @@ public override bool IsReadOnly } // Gets the collection of XmlEntity nodes declared in the document type declaration. - public XmlNamedNodeMap Entities => _entities ??= new XmlNamedNodeMap(this); + public XmlNamedNodeMap Entities => field ??= new XmlNamedNodeMap(this); // Gets the collection of XmlNotation nodes present in the document type declaration. - public XmlNamedNodeMap Notations => _notations ??= new XmlNamedNodeMap(this); + public XmlNamedNodeMap Notations => field ??= new XmlNamedNodeMap(this); // // DOM Level 2 diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs index a877febf910fcb..f75d1a470629f9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs @@ -42,8 +42,7 @@ internal sealed class ValidationState public bool HasMatched; // whether the element has been verified correctly //For NFAs - private BitSet[]? _curPos; - public BitSet[] CurPos => _curPos ??= new BitSet[2]; + public BitSet[] CurPos => field ??= new BitSet[2]; //For all public BitSet? AllElementsSet; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index c9c5e9df337479..3ea8ae0addb237 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -35,24 +35,16 @@ public class XmlSchema : XmlSchemaObject private bool _isPreprocessed; private bool _isRedefined; private int _errorCount; - private XmlSchemaObjectTable? _attributes; - private XmlSchemaObjectTable _attributeGroups = new XmlSchemaObjectTable(); - private XmlSchemaObjectTable _elements = new XmlSchemaObjectTable(); - private XmlSchemaObjectTable _types = new XmlSchemaObjectTable(); private readonly XmlSchemaObjectTable _groups = new XmlSchemaObjectTable(); private readonly XmlSchemaObjectTable _notations = new XmlSchemaObjectTable(); private readonly XmlSchemaObjectTable _identityConstraints = new XmlSchemaObjectTable(); private static int s_globalIdCounter = -1; - private ArrayList? _importedSchemas; - private ArrayList? _importedNamespaces; private int _schemaId = -1; //Not added to a set private Uri? _baseUri; private bool _isChameleon; private readonly Hashtable _ids = new Hashtable(); - private XmlDocument? _document; - private XmlNameTable? _nameTable; public XmlSchema() { } @@ -330,16 +322,16 @@ internal bool IsRedefined } [XmlIgnore] - public XmlSchemaObjectTable Attributes => _attributes ??= new XmlSchemaObjectTable(); + public XmlSchemaObjectTable Attributes => field ??= new XmlSchemaObjectTable(); [XmlIgnore] - public XmlSchemaObjectTable AttributeGroups => _attributeGroups ??= new XmlSchemaObjectTable(); + public XmlSchemaObjectTable AttributeGroups => field ??= new XmlSchemaObjectTable(); [XmlIgnore] - public XmlSchemaObjectTable SchemaTypes => _types ??= new XmlSchemaObjectTable(); + public XmlSchemaObjectTable SchemaTypes => field ??= new XmlSchemaObjectTable(); [XmlIgnore] - public XmlSchemaObjectTable Elements => _elements ??= new XmlSchemaObjectTable(); + public XmlSchemaObjectTable Elements => field ??= new XmlSchemaObjectTable(); [XmlAttribute("id", DataType = "ID")] public string? Id @@ -416,7 +408,7 @@ internal Hashtable Ids } [XmlIgnore] - internal XmlDocument Document => _document ??= new XmlDocument(); + internal XmlDocument Document => field ??= new XmlDocument(); [XmlIgnore] internal int ErrorCount @@ -518,11 +510,11 @@ internal override void AddAnnotation(XmlSchemaAnnotation annotation) _items.Add(annotation); } - internal XmlNameTable NameTable => _nameTable ??= new System.Xml.NameTable(); + internal XmlNameTable NameTable => field ??= new System.Xml.NameTable(); - internal ArrayList ImportedSchemas => _importedSchemas ??= new ArrayList(); + internal ArrayList ImportedSchemas => field ??= new ArrayList(); - internal ArrayList ImportedNamespaces => _importedNamespaces ??= new ArrayList(); + internal ArrayList ImportedNamespaces => field ??= new ArrayList(); internal static void GetExternalSchemasList(IList extList, XmlSchema schema) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs index 62c070ba593c44..96cbb48dc20d8b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs @@ -11,7 +11,6 @@ public abstract class XmlSchemaObject private int _lineNum; private int _linePos; private string? _sourceUri; - private XmlSerializerNamespaces? _namespaces; private XmlSchemaObject? _parent; //internal @@ -48,8 +47,8 @@ public XmlSchemaObject? Parent [XmlNamespaceDeclarations] public XmlSerializerNamespaces Namespaces { - get => _namespaces ??= new XmlSerializerNamespaces(); - set => _namespaces = value; + get => field ??= new XmlSerializerNamespaces(); + set => field = value; } internal virtual void OnAdd(XmlSchemaObjectCollection container, object? item) { } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 614f0b511ac14f..a58813263729f9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -16,9 +16,6 @@ namespace System.Xml.Serialization public class ImportContext { private readonly bool _shareTypes; - private SchemaObjectCache? _cache; // cached schema top-level items - private Hashtable? _mappings; // XmlSchema -> SerializableMapping, XmlSchemaSimpleType -> EnumMapping, XmlSchemaComplexType -> StructMapping - private Hashtable? _elements; // XmlSchemaElement -> ElementAccessor private CodeIdentifiers? _typeIdentifiers; public ImportContext(CodeIdentifiers? identifiers, bool shareTypes) @@ -29,11 +26,11 @@ public ImportContext(CodeIdentifiers? identifiers, bool shareTypes) internal ImportContext() : this(null, false) { } - internal SchemaObjectCache Cache => _cache ??= new SchemaObjectCache(); + internal SchemaObjectCache Cache => field ??= new SchemaObjectCache(); // cached schema top-level items - internal Hashtable Elements => _elements ??= new Hashtable(); + internal Hashtable Elements => field ??= new Hashtable(); // XmlSchemaElement -> ElementAccessor - internal Hashtable Mappings => _mappings ??= new Hashtable(); + internal Hashtable Mappings => field ??= new Hashtable(); // XmlSchema -> SerializableMapping, XmlSchemaSimpleType -> EnumMapping, XmlSchemaComplexType -> StructMapping public CodeIdentifiers TypeIdentifiers => _typeIdentifiers ??= new CodeIdentifiers(); @@ -50,19 +47,15 @@ public StringCollection Warnings internal sealed class SchemaObjectCache { - private Hashtable? _graph; - private Hashtable? _hash; - private Hashtable? _objectCache; - private StringCollection? _warnings; // UNDONE remove me soon, this is debug only code internal Hashtable looks = new Hashtable(); - private Hashtable Graph => _graph ??= new Hashtable(); + private Hashtable Graph => field ??= new Hashtable(); - private Hashtable Hash => _hash ??= new Hashtable(); + private Hashtable Hash => field ??= new Hashtable(); - private Hashtable ObjectCache => _objectCache ??= new Hashtable(); + private Hashtable ObjectCache => field ??= new Hashtable(); - internal StringCollection Warnings => _warnings ??= new StringCollection(); + internal StringCollection Warnings => field ??= new StringCollection(); internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index 0861f1d78f76bd..e9eb811cf3fffa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -476,7 +476,6 @@ internal sealed class StructMapping : TypeMapping, INameScope private bool _isSequence; private NameTable? _elements; private NameTable? _attributes; - private CodeIdentifiers? _scope; [DisallowNull] internal StructMapping? BaseMapping @@ -577,8 +576,8 @@ internal bool IsOpenModel internal CodeIdentifiers Scope { - get => _scope ??= new CodeIdentifiers(); - set => _scope = value; + get => field ??= new CodeIdentifiers(); + set => field = value; } internal MemberMapping? FindDeclaringMapping(MemberMapping member, out StructMapping? declaringMapping, string? parent) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 6d3d27a55915a8..331d620f631a34 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -2387,7 +2387,6 @@ internal sealed class RecursionLimiter { private readonly int _maxDepth; private int _depth; - private WorkItems? _deferredWorkItems; internal RecursionLimiter() { @@ -2398,6 +2397,6 @@ internal RecursionLimiter() internal bool IsExceededLimit { get { return _depth > _maxDepth; } } internal int Depth { get { return _depth; } set { _depth = value; } } - internal WorkItems DeferredWorkItems => _deferredWorkItems ??= new WorkItems(); + internal WorkItems DeferredWorkItems => field ??= new WorkItems(); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 951a3906624b2d..7de7d8d58f7f63 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -21,10 +21,8 @@ namespace System.Xml.Serialization public class XmlSchemas : CollectionBase, IEnumerable { private XmlSchemaSet? _schemaSet; - private Hashtable? _references; private SchemaObjectCache? _cache; // cached schema top-level items private bool _shareTypes; - private Hashtable? _mergedSchemas; internal Hashtable delayedSchemas = new Hashtable(); private bool _isCompiled; private static volatile XmlSchema? s_xsd; @@ -57,9 +55,9 @@ public IList GetSchemas(string? ns) internal SchemaObjectCache Cache => _cache ??= new SchemaObjectCache(); - internal Hashtable MergedSchemas => _mergedSchemas ??= new Hashtable(); + internal Hashtable MergedSchemas => field ??= new Hashtable(); - internal Hashtable References => _references ??= new Hashtable(); + internal Hashtable References => field ??= new Hashtable(); internal XmlSchemaSet SchemaSet { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index ff27357ebba28a..93e3889be7e24d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -2043,12 +2043,11 @@ public object CollectionItems internal sealed class XmlSerializationReaderCodeGen : XmlSerializationCodeGen { private readonly Hashtable _idNames = new Hashtable(); - private Hashtable? _enums; private readonly Hashtable _createMethods = new Hashtable(); private int _nextCreateMethodNumber; private int _nextIdNumber; - internal Hashtable Enums => _enums ??= new Hashtable(); + internal Hashtable Enums => field ??= new Hashtable(); private sealed class CreateCollectionInfo { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index a017539611908c..6032b1ebc8cc13 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -23,10 +23,9 @@ internal sealed partial class XmlSerializationReaderILGen : XmlSerializationILGe private readonly Dictionary _idNames = new Dictionary(); // Mapping name->id_XXXNN field private readonly Dictionary _idNameFields = new Dictionary(); - private Dictionary? _enums; private int _nextIdNumber; - internal Dictionary Enums => _enums ??= new Dictionary(); + internal Dictionary Enums => field ??= new Dictionary(); private static readonly string[] s_checkTypeString = new string[] { "checkType" }; private static readonly Type[] s_boolType = new Type[] { typeof(bool) }; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs index 7346cadcd902e9..824156c3c5cb47 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs @@ -54,7 +54,6 @@ internal sealed class XmlILConstructInfo : IQilAnnotation private bool _isNmspInScope, _mightHaveNmsp, _mightHaveAttrs, _mightHaveDupAttrs, _mightHaveNmspAfterAttrs; private XmlILConstructMethod _constrMeth; private XmlILConstructInfo? _parentInfo; - private ArrayList? _callersInfo; private bool _isReadOnly; private static volatile XmlILConstructInfo? s_default; @@ -359,7 +358,7 @@ public bool MightHaveDuplicateAttributes /// This annotation is only applicable to Function nodes. It contains a list of XmlILConstructInfo annotations /// for all QilInvoke nodes which call the annotated function. /// - public ArrayList CallersInfo => _callersInfo ??= new ArrayList(); + public ArrayList CallersInfo => field ??= new ArrayList(); /// /// Return name of this annotation. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs index 32af222ca8b7c9..b2c1254412ce50 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs @@ -91,7 +91,6 @@ internal enum OutputResult #pragma warning restore 618 private readonly Hashtable _scriptExtensions; - private ArrayList? _numberList; // // Template lookup action // @@ -303,7 +302,7 @@ internal void ReleaseSharedStringBuilder() } #pragma warning restore CA1822 - internal ArrayList NumberList => _numberList ??= new ArrayList(); + internal ArrayList NumberList => field ??= new ArrayList(); internal IXsltDebugger? Debugger { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs index 338fc89fd409a8..e4925381fe629c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/RootAction.cs @@ -83,9 +83,8 @@ internal sealed class RootAction : TemplateBaseAction private readonly Hashtable _attributeSetTable = new Hashtable(); private readonly Hashtable _decimalFormatTable = new Hashtable(); private List? _keyList; - private XsltOutput? _output; - internal XsltOutput Output => _output ??= new XsltOutput(); + internal XsltOutput Output => field ??= new XsltOutput(); /* * Compile diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs index 95ee34ab4504b6..7edd10c45b0b48 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomType.cs @@ -11,8 +11,6 @@ namespace System.Reflection.Context.Custom { internal sealed class CustomType : ProjectingType { - private IEnumerable? _newProperties; - public CustomType(Type template, CustomReflectionContext context) : base(template, context.Projector) { @@ -282,6 +280,6 @@ public override MethodInfo[] GetMethods(BindingFlags bindingAttr) } } - private IEnumerable NewProperties => _newProperties ??= ReflectionContext.GetNewPropertiesForType(this); + private IEnumerable NewProperties => field ??= ReflectionContext.GetNewPropertiesForType(this); } } diff --git a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/TypeBuilderImpl.cs b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/TypeBuilderImpl.cs index 9bb4d7613298a1..dd2219f54339b9 100644 --- a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/TypeBuilderImpl.cs +++ b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/TypeBuilderImpl.cs @@ -15,7 +15,6 @@ internal sealed class TypeBuilderImpl : TypeBuilder private readonly ModuleBuilderImpl _module; private readonly string _name; private readonly string? _namespace; - private string? _strFullName; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] private Type? _typeParent; private readonly TypeBuilderImpl? _declaringType; @@ -600,7 +599,7 @@ public override Type GetGenericTypeDefinition() // You will never have to deal with a TypeBuilder if you are just referring to arrays. public override Type GetElementType() => throw new NotSupportedException(SR.NotSupported_DynamicModule); public override string? AssemblyQualifiedName => throw new NotSupportedException(); - public override string? FullName => _strFullName ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); + public override string? FullName => field ??= TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); public override string? Namespace => _namespace; public override Assembly Assembly => _module.Assembly; public override Module Module => _module; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs index 8e85330e19d26f..05acfef523df4b 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/RoAssembly.cs @@ -38,8 +38,7 @@ protected RoAssembly(MetadataLoadContext loader, int assemblyFileCount) protected abstract AssemblyNameData ComputeNameData(); private volatile AssemblyNameData? _lazyAssemblyNameData; - public sealed override string FullName => _lazyFullName ??= GetName().FullName; - private volatile string? _lazyFullName; + public sealed override string FullName => field ??= GetName().FullName; internal const string ThrowingMessageInRAF = "This member throws an exception for assemblies embedded in a single-file app"; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Constructors/RoConstructor.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Constructors/RoConstructor.cs index 22459dee2c3192..4054f3bab551d8 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Constructors/RoConstructor.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Constructors/RoConstructor.cs @@ -21,9 +21,8 @@ protected RoConstructor() { } public sealed override Type ReflectedType => DeclaringType; - public sealed override string Name => _lazyName ??= ComputeName(); + public sealed override string Name => field ??= ComputeName(); protected abstract string ComputeName(); - private volatile string? _lazyName; public sealed override Module Module => GetRoModule(); internal abstract RoModule GetRoModule(); @@ -65,9 +64,8 @@ protected RoConstructor() { } public sealed override ParameterInfo[] GetParameters() => GetParametersNoCopy().CloneArray(); internal RoParameter[] GetParametersNoCopy() => MethodSig.Parameters; - private MethodSig MethodSig => _lazyMethodSig ??= ComputeMethodSig(); + private MethodSig MethodSig => field ??= ComputeMethodSig(); protected abstract MethodSig ComputeMethodSig(); - private volatile MethodSig? _lazyMethodSig; public sealed override string ToString() => Loader.GetDisposedString() ?? this.ToString(ComputeMethodSigStrings()); protected abstract MethodSig ComputeMethodSigStrings(); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/CustomAttributes/RoCustomAttributeData.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/CustomAttributes/RoCustomAttributeData.cs index 0921581bc4ccb6..2db22bd8cb26f8 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/CustomAttributes/RoCustomAttributeData.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/CustomAttributes/RoCustomAttributeData.cs @@ -12,13 +12,11 @@ internal abstract partial class RoCustomAttributeData : LeveledCustomAttributeDa { protected RoCustomAttributeData() { } - public sealed override Type AttributeType => _lazyAttributeType ??= ComputeAttributeType()!; + public sealed override Type AttributeType => field ??= ComputeAttributeType()!; protected abstract Type? ComputeAttributeType(); - private volatile Type? _lazyAttributeType; - public sealed override ConstructorInfo Constructor => _lazyConstructorInfo ??= ComputeConstructor(); + public sealed override ConstructorInfo Constructor => field ??= ComputeConstructor(); protected abstract ConstructorInfo ComputeConstructor(); - private volatile ConstructorInfo? _lazyConstructorInfo; public abstract override IList ConstructorArguments { get; } public abstract override IList NamedArguments { get; } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Events/RoEvent.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Events/RoEvent.cs index 9fd2eaeac53393..30661e288c8654 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Events/RoEvent.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Events/RoEvent.cs @@ -32,9 +32,8 @@ protected RoEvent(RoInstantiationProviderType declaringType, Type reflectedType) public sealed override Type ReflectedType => _reflectedType; - public sealed override string Name => _lazyName ??= ComputeName(); + public sealed override string Name => field ??= ComputeName(); protected abstract string ComputeName(); - private volatile string? _lazyName; public sealed override Module Module => GetRoModule(); internal abstract RoModule GetRoModule(); @@ -50,9 +49,8 @@ protected RoEvent(RoInstantiationProviderType declaringType, Type reflectedType) private const EventAttributes EventAttributesSentinel = (EventAttributes)(-1); private volatile EventAttributes _lazyEventAttributes = EventAttributesSentinel; - public sealed override Type EventHandlerType => _lazyEventType ??= ComputeEventHandlerType(); + public sealed override Type EventHandlerType => field ??= ComputeEventHandlerType(); protected abstract Type ComputeEventHandlerType(); - private volatile Type? _lazyEventType; private RoMethod? GetRoAddMethod() => (_lazyAdder == Sentinels.RoMethod) ? (_lazyAdder = ComputeEventAddMethod()?.FilterInheritedAccessor()) : _lazyAdder; private RoMethod? GetRoRemoveMethod() => (_lazyRemover == Sentinels.RoMethod) ? (_lazyRemover = ComputeEventRemoveMethod()?.FilterInheritedAccessor()) : _lazyRemover; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Fields/RoField.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Fields/RoField.cs index 0162946f31cf80..76a11c658bf837 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Fields/RoField.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Fields/RoField.cs @@ -34,9 +34,8 @@ protected RoField(RoInstantiationProviderType declaringType, Type reflectedType) public sealed override Type ReflectedType => _reflectedType; - public sealed override string Name => _lazyName ??= ComputeName(); + public sealed override string Name => field ??= ComputeName(); protected abstract string ComputeName(); - private volatile string? _lazyName; public sealed override Module Module => GetRoModule(); internal abstract RoModule GetRoModule(); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoMethod.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoMethod.cs index 0ef99f8ec934ce..374b4c3048898f 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoMethod.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Methods/RoMethod.cs @@ -29,9 +29,8 @@ protected RoMethod(Type reflectedType) public sealed override Type ReflectedType => _reflectedType; - public sealed override string Name => _lazyName ??= ComputeName(); + public sealed override string Name => field ??= ComputeName(); protected abstract string ComputeName(); - private volatile string? _lazyName; public sealed override Module Module => GetRoModule(); internal abstract RoModule GetRoModule(); @@ -90,9 +89,8 @@ public sealed override bool ContainsGenericParameters public sealed override ParameterInfo ReturnParameter => MethodSig.Return; internal RoParameter[] GetParametersNoCopy() => MethodSig.Parameters; - private MethodSig MethodSig => _lazyMethodSig ??= ComputeMethodSig(); + private MethodSig MethodSig => field ??= ComputeMethodSig(); protected abstract MethodSig ComputeMethodSig(); - private volatile MethodSig? _lazyMethodSig; public sealed override ICustomAttributeProvider ReturnTypeCustomAttributes => ReturnParameter; public sealed override Type ReturnType => ReturnParameter.ParameterType; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/Ecma/EcmaModule.MetadataTables.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/Ecma/EcmaModule.MetadataTables.cs index 6463a72aabcc3a..fbc14ab264876c 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/Ecma/EcmaModule.MetadataTables.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/Ecma/EcmaModule.MetadataTables.cs @@ -36,38 +36,20 @@ private void EnsureTypeDefTableFullyFilled() } private bool _typeDefTableFullyFilled; // Only gets set true if EnsureTypeDefTableFullyFilled() fills the table. False negative just means some unnecessary work is done. - internal MetadataTable TypeRefTable - { - get - { - return _lazyTypeRefTable ?? - Interlocked.CompareExchange(ref _lazyTypeRefTable, CreateTable(TableIndex.TypeRef), null) ?? - _lazyTypeRefTable; - } - } - private volatile MetadataTable? _lazyTypeRefTable; + internal MetadataTable TypeRefTable => + field ?? + Interlocked.CompareExchange(ref field, CreateTable(TableIndex.TypeRef), null) ?? + field; - internal MetadataTable GenericParamTable - { - get - { - return _lazyGenericParamTable ?? - Interlocked.CompareExchange(ref _lazyGenericParamTable, CreateTable(TableIndex.GenericParam), null) ?? - _lazyGenericParamTable; - } - } - private volatile MetadataTable? _lazyGenericParamTable; + internal MetadataTable GenericParamTable => + field ?? + Interlocked.CompareExchange(ref field, CreateTable(TableIndex.GenericParam), null) ?? + field; - internal MetadataTable AssemblyRefTable - { - get - { - return _lazyAssemblyRefTable ?? - Interlocked.CompareExchange(ref _lazyAssemblyRefTable, CreateTable(TableIndex.AssemblyRef), null) ?? - _lazyAssemblyRefTable; - } - } - private volatile MetadataTable? _lazyAssemblyRefTable; + internal MetadataTable AssemblyRefTable => + field ?? + Interlocked.CompareExchange(ref field, CreateTable(TableIndex.AssemblyRef), null) ?? + field; private MetadataTable CreateTable(TableIndex tableIndex) where T : class { diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/RoFatMethodParameter.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/RoFatMethodParameter.cs index 35a341e2e7e6c1..71c718a2ab0176 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/RoFatMethodParameter.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Parameters/RoFatMethodParameter.cs @@ -19,9 +19,8 @@ protected RoFatMethodParameter(IRoMethodBase roMethodBase, int position, Type pa Debug.Assert(parameterType != null); } - public sealed override string? Name => _lazyName ??= ComputeName(); + public sealed override string? Name => field ??= ComputeName(); protected abstract string? ComputeName(); - private volatile string? _lazyName; public sealed override ParameterAttributes Attributes => (_lazyParameterAttributes == ParameterAttributesSentinel) ? (_lazyParameterAttributes = ComputeAttributes()) : _lazyParameterAttributes; protected abstract ParameterAttributes ComputeAttributes(); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Properties/RoProperty.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Properties/RoProperty.cs index 68bbe696edadec..e4a0cafd49f409 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Properties/RoProperty.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Properties/RoProperty.cs @@ -33,9 +33,8 @@ protected RoProperty(RoInstantiationProviderType declaringType, Type reflectedTy public sealed override Type ReflectedType => _reflectedType; - public sealed override string Name => _lazyName ??= ComputeName(); + public sealed override string Name => field ??= ComputeName(); protected abstract string ComputeName(); - private volatile string? _lazyName; public sealed override Module Module => GetRoModule(); internal abstract RoModule GetRoModule(); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs index 2bccecb7930715..c126af79b3a27c 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs @@ -204,9 +204,7 @@ private static bool NeedToSearchImmediateTypeOnly(BindingFlags bf) return true; } - private TypeComponentsCache Cache => _lazyCache ??= new TypeComponentsCache(this); - - private volatile TypeComponentsCache? _lazyCache; + private TypeComponentsCache Cache => field ??= new TypeComponentsCache(this); private const int GenericParameterCountAny = -1; } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.cs index 1a5369f2f638d1..ed305fc921a093 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Types/RoType.cs @@ -105,21 +105,18 @@ public override Type[] GetFunctionPointerCallingConventions() protected internal abstract RoType[] GetGenericArgumentsNoCopy(); // Naming - public sealed override string Name => _lazyName ??= ComputeName(); + public sealed override string Name => field ??= ComputeName(); protected abstract string ComputeName(); internal string Call_ComputeName() => ComputeName(); - private volatile string? _lazyName; - public sealed override string? Namespace => _lazyNamespace ??= ComputeNamespace(); + public sealed override string? Namespace => field ??= ComputeNamespace(); protected abstract string? ComputeNamespace(); internal string? Call_ComputeNamespace() => ComputeNamespace(); - private volatile string? _lazyNamespace; - public sealed override string? FullName => _lazyFullName ??= ComputeFullName(); + public sealed override string? FullName => field ??= ComputeFullName(); protected abstract string? ComputeFullName(); internal string? Call_ComputeFullName() => ComputeFullName(); - private volatile string? _lazyFullName; - public override string? AssemblyQualifiedName => _lazyAssemblyQualifiedFullName ??= ComputeAssemblyQualifiedName(); + public override string? AssemblyQualifiedName => field ??= ComputeAssemblyQualifiedName(); private string? ComputeAssemblyQualifiedName() { string? fullName = FullName; @@ -128,7 +125,6 @@ public override Type[] GetFunctionPointerCallingConventions() string? assemblyName = Assembly.FullName; return fullName + ", " + assemblyName; } - private volatile string? _lazyAssemblyQualifiedFullName; // Assembly and module public sealed override Assembly Assembly => Module.Assembly; diff --git a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/BinaryFormat/BinaryFormattedObject.cs b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/BinaryFormat/BinaryFormattedObject.cs index 56b18143815201..8d4f9ecdaa1916 100644 --- a/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/BinaryFormat/BinaryFormattedObject.cs +++ b/src/libraries/System.Resources.Extensions/src/System/Resources/Extensions/BinaryFormat/BinaryFormattedObject.cs @@ -33,8 +33,7 @@ internal sealed partial class BinaryFormattedObject }; private readonly Options _options; - private ITypeResolver? _typeResolver; - private ITypeResolver TypeResolver => _typeResolver ??= new DefaultTypeResolver(_options); + private ITypeResolver TypeResolver => field ??= new DefaultTypeResolver(_options); /// /// Creates by parsing . diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs index 79e06d1243a5d2..179ebda6776e20 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheItemPolicy.cs @@ -10,7 +10,6 @@ public class CacheItemPolicy { private DateTimeOffset _absExpiry; private TimeSpan _sldExpiry; - private Collection _changeMonitors; private CacheItemPriority _priority; private CacheEntryRemovedCallback _removedCallback; private CacheEntryUpdateCallback _updateCallback; @@ -21,7 +20,7 @@ public DateTimeOffset AbsoluteExpiration set { _absExpiry = value; } } - public Collection ChangeMonitors => _changeMonitors ??= new Collection(); + public Collection ChangeMonitors => field ??= new Collection(); public CacheItemPriority Priority { diff --git a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportGlobals.cs b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportGlobals.cs index 59392aed8b04f1..0cc9bfb7da1b17 100644 --- a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportGlobals.cs +++ b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportGlobals.cs @@ -84,30 +84,14 @@ internal static class ImportGlobals public const string ValueNameProperty = "ValueName"; public const string ValueProperty = "Value"; - private static Uri? s_dataContractXsdBaseNamespaceUri; - internal static Uri DataContractXsdBaseNamespaceUri => s_dataContractXsdBaseNamespaceUri ??= new Uri(DataContractXsdBaseNamespace); - - private static XmlQualifiedName? s_idQualifiedName; - internal static XmlQualifiedName IdQualifiedName => s_idQualifiedName ??= new XmlQualifiedName(ImportGlobals.IdLocalName, ImportGlobals.SerializationNamespace); - - private static XmlQualifiedName? s_refQualifiedName; - internal static XmlQualifiedName RefQualifiedName => s_refQualifiedName ??= new XmlQualifiedName(ImportGlobals.RefLocalName, ImportGlobals.SerializationNamespace); - - private static Type? s_typeOfXmlElement; - internal static Type TypeOfXmlElement => s_typeOfXmlElement ??= typeof(XmlElement); - - private static Type? s_typeOfXmlNodeArray; - internal static Type TypeOfXmlNodeArray => s_typeOfXmlNodeArray ??= typeof(XmlNode[]); - - private static Type? s_typeOfXmlQualifiedName; - internal static Type TypeOfXmlQualifiedName => s_typeOfXmlQualifiedName ??= typeof(XmlQualifiedName); - - private static Type? s_typeOfXmlSchemaProviderAttribute; - internal static Type TypeOfXmlSchemaProviderAttribute => s_typeOfXmlSchemaProviderAttribute ??= typeof(XmlSchemaProviderAttribute); - - private static Type? s_typeOfXmlSchemaType; - internal static Type TypeOfXmlSchemaType => s_typeOfXmlSchemaType ??= typeof(XmlSchemaType); - + internal static Uri DataContractXsdBaseNamespaceUri => field ??= new Uri(DataContractXsdBaseNamespace); + internal static XmlQualifiedName IdQualifiedName => field ??= new XmlQualifiedName(ImportGlobals.IdLocalName, ImportGlobals.SerializationNamespace); + internal static XmlQualifiedName RefQualifiedName => field ??= new XmlQualifiedName(ImportGlobals.RefLocalName, ImportGlobals.SerializationNamespace); + internal static Type TypeOfXmlElement => field ??= typeof(XmlElement); + internal static Type TypeOfXmlNodeArray => field ??= typeof(XmlNode[]); + internal static Type TypeOfXmlQualifiedName => field ??= typeof(XmlQualifiedName); + internal static Type TypeOfXmlSchemaProviderAttribute => field ??= typeof(XmlSchemaProviderAttribute); + internal static Type TypeOfXmlSchemaType => field ??= typeof(XmlSchemaType); public const string SerializationSchema = @" diff --git a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportOptions.cs b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportOptions.cs index 0e8fab9d0df5b9..b6fe6ce44729e2 100644 --- a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportOptions.cs +++ b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/ImportOptions.cs @@ -16,10 +16,6 @@ namespace System.Runtime.Serialization /// public class ImportOptions { - private ICollection? _referencedTypes; - private ICollection? _referencedCollectionTypes; - private IDictionary? _namespaces; - /// /// Gets or sets a instance that provides the means to check whether particular options for a target language are supported. /// @@ -57,16 +53,16 @@ public class ImportOptions /// /// Gets a dictionary that contains the mapping of data contract namespaces to the CLR namespaces that must be used to generate code during an import operation. /// - public IDictionary Namespaces => _namespaces ??= new Dictionary(); + public IDictionary Namespaces => field ??= new Dictionary(); /// /// Gets a collection of types that represents data contract collections that should be referenced when generating code for collections, such as lists or dictionaries of items. /// - public ICollection ReferencedCollectionTypes => _referencedCollectionTypes ??= new List(); + public ICollection ReferencedCollectionTypes => field ??= new List(); /// /// Gets a containing types referenced in generated code. /// - public ICollection ReferencedTypes => _referencedTypes ??= new List(); + public ICollection ReferencedTypes => field ??= new List(); } } diff --git a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/XsdDataContractImporter.cs b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/XsdDataContractImporter.cs index 5e9eba22fbf18c..43beae4cea959f 100644 --- a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/XsdDataContractImporter.cs +++ b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/XsdDataContractImporter.cs @@ -358,8 +358,7 @@ private bool InternalCanImport(XmlSchemaSet schemas, ICollection s_actualTypeAnnotationName ??= new XmlQualifiedName(ImportGlobals.ActualTypeLocalName, ImportGlobals.SerializationNamespace); + internal static XmlQualifiedName ActualTypeAnnotationName => field ??= new XmlQualifiedName(ImportGlobals.ActualTypeLocalName, ImportGlobals.SerializationNamespace); internal static XmlQualifiedName ImportActualType(XmlSchemaAnnotation? annotation, XmlQualifiedName defaultTypeName, XmlQualifiedName typeName) { diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs index 158078cd60afed..74f2019d453034 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs @@ -750,8 +750,7 @@ public class TypeWithSchemaFormInXmlAttribute public class CustomDocument { - private XmlDocument? _doc; - public XmlDocument Document => _doc ??= new XmlDocument(); + public XmlDocument Document => field ??= new XmlDocument(); [XmlAnyElement] public XmlNode[] Items diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Reflection/NullabilityInfoContextTests.cs b/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Reflection/NullabilityInfoContextTests.cs index aad27ed900cfaa..25e80df1fa867e 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Reflection/NullabilityInfoContextTests.cs +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests/System/Reflection/NullabilityInfoContextTests.cs @@ -896,12 +896,12 @@ public void NullablePublicOnlyStringTypeTest(string methodName, NullabilityState [SkipOnMono("Nullability attributes trimmed on Mono")] public void NullablePublicOnlyOtherTypesTest() { - Type type = typeof(Type); - FieldInfo privateNullableField = type.GetField("s_defaultBinder", flags)!; + FieldInfo privateNullableField = typeof(AppDomain).GetField("s_domain", flags)!; NullabilityInfo info = nullabilityContext.Create(privateNullableField); Assert.Equal(NullabilityState.Unknown, info.ReadState); Assert.Equal(NullabilityState.Unknown, info.WriteState); + Type type = typeof(Type); MethodInfo internalNotNullableMethod = type.GetMethod("GetRootElementType", flags)!; info = nullabilityContext.Create(internalNotNullableMethod.ReturnParameter); Assert.Equal(NullabilityState.NotNull, info.ReadState); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs index b4646648f50fcd..ed21cbb5d46551 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedKey.cs @@ -8,34 +8,30 @@ namespace System.Security.Cryptography.Xml { public sealed class EncryptedKey : EncryptedType { - private string? _recipient; - private string? _carriedKeyName; - private ReferenceList? _referenceList; - public EncryptedKey() { } [AllowNull] public string Recipient { - get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty + get => field ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty set { - _recipient = value; + field = value; _cachedXml = null; } } public string? CarriedKeyName { - get { return _carriedKeyName; } + get => field; set { - _carriedKeyName = value; + field = value; _cachedXml = null; } } - public ReferenceList ReferenceList => _referenceList ??= new ReferenceList(); + public ReferenceList ReferenceList => field ??= new ReferenceList(); public void AddReference(DataReference dataReference) { diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs index a65053b711fdc0..6b8bc562617a56 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedReference.cs @@ -10,7 +10,6 @@ public abstract class EncryptedReference { private string _uri; private string? _referenceType; - private TransformChain? _transformChain; internal XmlElement? _cachedXml; protected EncryptedReference() : this(string.Empty, new TransformChain()) @@ -44,10 +43,10 @@ public string Uri public TransformChain TransformChain { - get => _transformChain ??= new TransformChain(); + get => field ??= new TransformChain(); set { - _transformChain = value; + field = value; _cachedXml = null; } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs index 29aa30afacfec7..77d2ad8f85848f 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedType.cs @@ -13,9 +13,7 @@ public abstract class EncryptedType private string? _mimeType; private string? _encoding; private EncryptionMethod? _encryptionMethod; - private CipherData? _cipherData; private EncryptionPropertyCollection? _props; - private KeyInfo? _keyInfo; internal XmlElement? _cachedXml; [MemberNotNullWhen(true, nameof(_cachedXml))] @@ -70,8 +68,8 @@ public virtual string? Encoding [AllowNull] public KeyInfo KeyInfo { - get => _keyInfo ??= new KeyInfo(); - set => _keyInfo = value; + get => field ??= new KeyInfo(); + set => field = value; } public virtual EncryptionMethod? EncryptionMethod @@ -93,13 +91,13 @@ public void AddProperty(EncryptionProperty ep) public virtual CipherData CipherData { - get => _cipherData ??= new CipherData(); + get => field ??= new CipherData(); set { if (value == null) throw new ArgumentNullException(nameof(value)); - _cipherData = value; + field = value; _cachedXml = null; } } diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs index 706c112f2e9e44..bdbea9731e876d 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs @@ -69,7 +69,6 @@ public class EncryptedXml private PaddingMode _padding; private CipherMode _mode; private Encoding _encoding; - private string? _recipient; private int _xmlDsigSearchDepthCounter; private int _xmlDsigSearchDepth; @@ -172,8 +171,8 @@ public Encoding Encoding [AllowNull] public string Recipient { - get => _recipient ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty - set => _recipient = value; + get => field ??= string.Empty; // an unspecified value for an XmlAttribute is string.Empty + set => field = value; } // diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs index f42e5293d17347..57e2a81c56baed 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs @@ -45,9 +45,6 @@ public class SignedXml private const string XmlDsigMoreHMACSHA512Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; private const string XmlDsigMoreHMACRIPEMD160Url = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"; - // defines the XML encryption processing rules - private EncryptedXml? _exml; - // // public constant Url identifiers most frequently used within the XML Signature classes // @@ -177,8 +174,8 @@ public EncryptedXml EncryptedXml { [UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "ctors are marked as RDC")] [UnconditionalSuppressMessage("ILLink", "IL2026:RequiresUnreferencedCode", Justification = "ctors are marked as RUC")] - get => _exml ??= new EncryptedXml(_containingDocument!); // default processing rules - set => _exml = value; + get => field ??= new EncryptedXml(_containingDocument!); // default processing rules + set => field = value; } public Signature Signature diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs index c8179c064a9adb..8a078fddce62ad 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs @@ -30,7 +30,6 @@ public partial class Regex : ISerializable protected internal string[]? capslist; // if captures are sparse or named captures are used, this is the sorted list of names protected internal int capsize; // the size of the capture array - private WeakReference? _replref; // cached parsed replacement pattern private volatile RegexRunner? _runner; // cached runner #if DEBUG @@ -396,9 +395,9 @@ public int GroupNumberFromName(string name) /// A weak reference to a regex replacement, lazily initialized. internal WeakReference RegexReplacementWeakReference => - _replref ?? - Interlocked.CompareExchange(ref _replref, new WeakReference(null), null) ?? - _replref; + field ?? + Interlocked.CompareExchange(ref field, new WeakReference(null), null) ?? + field; [Obsolete(Obsoletions.RegexExtensibilityImplMessage, DiagnosticId = Obsoletions.RegexExtensibilityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] [EditorBrowsable(EditorBrowsableState.Never)] diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs index c1948b957f9390..8ef87cbe14a99d 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs @@ -20,7 +20,6 @@ namespace System.Text.RegularExpressions [RequiresDynamicCode("Compiling a RegEx requires dynamic code.")] internal abstract class RegexCompiler { -#pragma warning disable CS9264 // nullability of `field`: https://github.com/dotnet/csharplang/issues/8425 private static FieldInfo RuntextstartField => field ??= RegexRunnerField("runtextstart"); private static FieldInfo RuntextposField => field ??= RegexRunnerField("runtextpos"); private static FieldInfo RuntrackposField => field ??= RegexRunnerField("runtrackpos"); @@ -103,7 +102,6 @@ internal abstract class RegexCompiler private static MethodInfo MathMinIntIntMethod => field ??= typeof(Math).GetMethod("Min", [typeof(int), typeof(int)])!; private static MethodInfo MemoryMarshalGetArrayDataReferenceSearchValuesMethod => field ??= typeof(MemoryMarshal).GetMethod("GetArrayDataReference", [Type.MakeGenericMethodParameter(0).MakeArrayType()])!.MakeGenericMethod(typeof(SearchValues))!; private static MethodInfo UnsafeAsMethod => field ??= typeof(Unsafe).GetMethod("As", [typeof(object)])!; -#pragma warning restore CS9264 // Note: // Single-range helpers like IsAsciiLetterLower, IsAsciiLetterUpper, IsAsciiDigit, and IsBetween aren't used here, as the IL generated for those diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs index d4240f61c1c320..e1af700b8db8ef 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs @@ -18,9 +18,6 @@ internal sealed class CharSetSolver : ISolver /// BDD for each ASCII character that returns true for that one character. /// This cache is shared amongst all CharSetSolver instances and is accessed in a thread-safe manner. private static readonly BDD?[] s_asciiCache = new BDD[128]; - /// BDD that returns true for every non-ASCII character. - /// This instance is shared amongst all CharSetSolver instances and is accessed in a thread-safe manner. - private static BDD? s_nonAscii; /// Cache of BDD instances created by this solver. /// @@ -38,12 +35,6 @@ internal sealed class CharSetSolver : ISolver /// private readonly Dictionary<(int op, BDD a, BDD? b), BDD> _operationCache = new(); // op is BooleanOperation; using int to reuse generic instantiation with _bddCache - /// Gets a BDD that contains every non-ASCII character. - public BDD NonAscii => - s_nonAscii ?? - Interlocked.CompareExchange(ref s_nonAscii, CreateBDDFromRange('\x80', '\uFFFF'), null) ?? - s_nonAscii; - /// Creates a BDD that contains only the specified character. public BDD CreateBDDFromChar(char c) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs index e33940b979707f..c71441a24a00a3 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs @@ -24,32 +24,15 @@ internal sealed class SymbolicRegexBuilder where TSet : IComparable, internal readonly SymbolicRegexNode _anyStar; internal readonly SymbolicRegexNode _anyStarLazy; - private SymbolicRegexNode? _epsilon; - internal SymbolicRegexNode Epsilon => _epsilon ??= SymbolicRegexNode.CreateEpsilon(this); - - private SymbolicRegexNode? _beginningAnchor; - internal SymbolicRegexNode BeginningAnchor => _beginningAnchor ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.BeginningAnchor); - - private SymbolicRegexNode? _endAnchor; - internal SymbolicRegexNode EndAnchor => _endAnchor ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EndAnchor); - - private SymbolicRegexNode? _endAnchorZ; - internal SymbolicRegexNode EndAnchorZ => _endAnchorZ ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EndAnchorZ); - - private SymbolicRegexNode? _endAnchorZReverse; - internal SymbolicRegexNode EndAnchorZReverse => _endAnchorZReverse ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EndAnchorZReverse); - - private SymbolicRegexNode? _bolAnchor; - internal SymbolicRegexNode BolAnchor => _bolAnchor ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.BOLAnchor); - - private SymbolicRegexNode? _eolAnchor; - internal SymbolicRegexNode EolAnchor => _eolAnchor ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EOLAnchor); - - private SymbolicRegexNode? _wbAnchor; - internal SymbolicRegexNode BoundaryAnchor => _wbAnchor ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.BoundaryAnchor); - - private SymbolicRegexNode? _nwbAnchor; - internal SymbolicRegexNode NonBoundaryAnchor => _nwbAnchor ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.NonBoundaryAnchor); + internal SymbolicRegexNode Epsilon => field ??= SymbolicRegexNode.CreateEpsilon(this); + internal SymbolicRegexNode BeginningAnchor => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.BeginningAnchor); + internal SymbolicRegexNode EndAnchor => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EndAnchor); + internal SymbolicRegexNode EndAnchorZ => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EndAnchorZ); + internal SymbolicRegexNode EndAnchorZReverse => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EndAnchorZReverse); + internal SymbolicRegexNode BolAnchor => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.BOLAnchor); + internal SymbolicRegexNode EolAnchor => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.EOLAnchor); + internal SymbolicRegexNode BoundaryAnchor => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.BoundaryAnchor); + internal SymbolicRegexNode NonBoundaryAnchor => field ??= SymbolicRegexNode.CreateAnchor(this, SymbolicRegexNodeKind.NonBoundaryAnchor); internal TSet _wordLetterForBoundariesSet; internal TSet _newLineSet; diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/UnicodeCategoryConditions.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/UnicodeCategoryConditions.cs index 6ad4f5a526c4be..f8679bd76b051b 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/UnicodeCategoryConditions.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/UnicodeCategoryConditions.cs @@ -15,8 +15,6 @@ internal static class UnicodeCategoryConditions /// Array containing lazily-initialized BDDs per defined UnicodeCategory value. private static readonly BDD?[] s_categories = new BDD[UnicodeCategoryValueCount]; - /// Lazily-initialized BDD for \s. - private static volatile BDD? s_whiteSpace; /// Lazily-initialized BDD for \w. private static volatile BDD? s_wordLetter; /// Lazily-initialized BDD for \b. @@ -39,9 +37,9 @@ public static BDD GetCategory(UnicodeCategory category) => /// Gets a that represents the \s character class. public static BDD WhiteSpace => - s_whiteSpace ?? - Interlocked.CompareExchange(ref s_whiteSpace, BDD.Deserialize(UnicodeCategoryRanges.SerializedWhitespaceBDD), null) ?? - s_whiteSpace; + field ?? + Interlocked.CompareExchange(ref field, BDD.Deserialize(UnicodeCategoryRanges.SerializedWhitespaceBDD), null) ?? + field; /// Gets a that represents the \w character class. /// \w is the union of the 8 categories: 0,1,2,3,4,5,8,18 diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index e88772583be0f2..b98f51e538188a 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -279,13 +279,8 @@ internal static IsolationLevel DefaultIsolationLevel } } - - private static DefaultSettingsSection? s_defaultSettings; - private static DefaultSettingsSection DefaultSettings => s_defaultSettings ??= DefaultSettingsSection.GetSection(); - - - private static MachineSettingsSection? s_machineSettings; - private static MachineSettingsSection MachineSettings => s_machineSettings ??= MachineSettingsSection.GetSection(); + private static DefaultSettingsSection DefaultSettings => field ??= DefaultSettingsSection.GetSection(); + private static MachineSettingsSection MachineSettings => field ??= MachineSettingsSection.GetSection(); private static bool s_defaultTimeoutValidated; private static long s_defaultTimeoutTicks; diff --git a/src/libraries/System.Windows.Extensions/src/System/Media/SystemSounds.cs b/src/libraries/System.Windows.Extensions/src/System/Media/SystemSounds.cs index a5042fc0242026..8ccaa446976d34 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Media/SystemSounds.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Media/SystemSounds.cs @@ -5,35 +5,10 @@ namespace System.Media { public static class SystemSounds { - private static SystemSound? s_asterisk; - private static SystemSound? s_beep; - private static SystemSound? s_exclamation; - private static SystemSound? s_hand; - private static SystemSound? s_question; - - public static SystemSound Asterisk - { - get => s_asterisk ??= new SystemSound(Interop.User32.MB_ICONASTERISK); - } - - public static SystemSound Beep - { - get => s_beep ??= new SystemSound(Interop.User32.MB_OK); - } - - public static SystemSound Exclamation - { - get => s_exclamation ??= new SystemSound(Interop.User32.MB_ICONEXCLAMATION); - } - - public static SystemSound Hand - { - get => s_hand ??= new SystemSound(Interop.User32.MB_ICONHAND); - } - - public static SystemSound Question - { - get => s_question ??= new SystemSound(Interop.User32.MB_ICONQUESTION); - } + public static SystemSound Asterisk => field ??= new SystemSound(Interop.User32.MB_ICONASTERISK); + public static SystemSound Beep => field ??= new SystemSound(Interop.User32.MB_OK); + public static SystemSound Exclamation => field ??= new SystemSound(Interop.User32.MB_ICONEXCLAMATION); + public static SystemSound Hand => field ??= new SystemSound(Interop.User32.MB_ICONHAND); + public static SystemSound Question => field ??= new SystemSound(Interop.User32.MB_ICONQUESTION); } }