From 06b6a0d1b25ad8d33f6525594cd8f470e18354e9 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Fri, 7 Feb 2020 16:09:38 -0800 Subject: [PATCH 1/9] Optimize ToUpperInvariant/ToLowerInvariant - Also optimize static field TextInfo.Invariant - Rewrite ToUpper/Lower(Invariant) call sites to use optimized method --- .../System/Data/Common/DbConnectionOptions.Common.cs | 4 ++-- .../Common/src/System/Drawing/ColorTranslator.cs | 2 +- .../VisualBasic/CompilerServices/LikeOperator.vb | 2 +- .../src/Microsoft/CSharp/CSharpCodeGenerator.cs | 2 +- .../Collections/Specialized/FixedStringLookup.cs | 2 +- .../ComponentModel/Design/DesigntimeLicenseContext.cs | 4 ++-- .../src/System/Configuration/ClientConfigPaths.cs | 2 +- .../src/System/Configuration/ConfigurationElement.cs | 2 +- .../src/System/Configuration/IdnElement.cs | 6 ++---- .../src/System/Data/Common/AdapterUtil.Common.cs | 6 +++--- .../src/System/Data/Common/DbConnectionOptions.cs | 2 +- .../System.Data.OleDb/src/DbConnectionOptions.cs | 6 +++--- .../System.Data.OleDb/src/OleDbCommandBuilder.cs | 2 +- .../System.Data.OleDb/src/OleDbConnectionString.cs | 2 +- .../src/OleDbConnectionStringBuilder.cs | 2 +- src/libraries/System.Data.OleDb/src/OleDbDataReader.cs | 4 ++-- src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs | 2 +- .../src/System/Diagnostics/InstanceDataCollection.cs | 6 +++--- .../Diagnostics/InstanceDataCollectionCollection.cs | 6 +++--- .../src/System/Diagnostics/PerformanceCounter.cs | 4 ++-- .../System/Diagnostics/PerformanceCounterCategory.cs | 2 +- .../AccountManagement/AD/ADStoreCtx.cs | 2 +- .../AccountManagement/SAM/SAMStoreCtx.cs | 2 +- .../AccountManagement/SAM/SAMStoreCtx_LoadStore.cs | 2 +- .../Protocols/common/DirectoryAttribute.cs | 6 +++--- .../ActiveDirectoryReplicationMetaData.cs | 6 +++--- .../ActiveDirectory/ActiveDirectorySchemaClass.cs | 4 ++-- .../ActiveDirectory/ActiveDirectorySiteLink.cs | 2 +- .../ActiveDirectory/ActiveDirectorySiteLinkBridge.cs | 2 +- .../ActiveDirectory/DirectoryServer.cs | 2 +- .../DirectoryServices/ActiveDirectory/Locator.cs | 4 ++-- .../System/DirectoryServices/ActiveDirectory/Utils.cs | 10 +++++----- .../src/System/DirectoryServices/DirectoryEntry.cs | 2 +- .../src/System/DirectoryServices/PropertyCollection.cs | 2 +- .../DirectoryServices/ResultPropertyCollection.cs | 6 +++--- .../src/System/Management/ManagementQuery.cs | 2 +- .../src/System/Management/WMIGenerator.cs | 8 ++++---- .../src/System/Net/HttpListenerRequest.cs | 2 +- .../src/System/Net/Mime/HeaderCollection.cs | 8 ++++---- .../src/System/Net/Mime/MimeMultiPart.cs | 2 +- .../src/System/Net/FtpWebRequest.cs | 2 +- .../System.Net.WebClient/src/System/Net/WebClient.cs | 2 +- .../System.Private.CoreLib/src/System/Char.cs | 4 ++-- .../src/System/Globalization/TextInfo.cs | 4 +--- .../src/System/String.Manipulation.cs | 4 ++-- .../src/System/Xml/Schema/XmlSchemaDataType.cs | 2 +- .../src/System/Xml/Serialization/CodeIdentifier.cs | 6 +++--- .../src/System/RuntimeType.Mono.cs | 4 ++-- 48 files changed, 84 insertions(+), 88 deletions(-) diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs index 939f62a3cc608c..b409b907c14fb1 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs @@ -153,7 +153,7 @@ private static string GetKeyName(StringBuilder buffer) { count--; // trailing whitespace } - return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture); + return buffer.ToString(0, count).ToLowerInvariant(); } private static string GetKeyValue(StringBuilder buffer, bool trimWhitespace) @@ -445,7 +445,7 @@ private static Dictionary SplitConnectionString(string connectio CaptureCollection keyvalues = match.Groups[ValueIndex].Captures; foreach (Capture keypair in match.Groups[KeyIndex].Captures) { - string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture); + string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant(); string keyvalue = keyvalues[indexValue++].Value; if (0 < keyvalue.Length) { diff --git a/src/libraries/Common/src/System/Drawing/ColorTranslator.cs b/src/libraries/Common/src/System/Drawing/ColorTranslator.cs index 47763c3a53cdf4..92d47565659592 100644 --- a/src/libraries/Common/src/System/Drawing/ColorTranslator.cs +++ b/src/libraries/Common/src/System/Drawing/ColorTranslator.cs @@ -260,7 +260,7 @@ public static Color FromHtml(string htmlColor) InitializeHtmlSysColorTable(); } - s_htmlSysColorTable!.TryGetValue(htmlColor.ToLower(CultureInfo.InvariantCulture), out c); + s_htmlSysColorTable!.TryGetValue(htmlColor.ToLowerInvariant(), out c); } // resort to type converter which will handle named colors diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb index d2a6d9b050bbae..6cf0e953472057 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/CompilerServices/LikeOperator.vb @@ -146,7 +146,7 @@ Namespace Microsoft.VisualBasic.CompilerServices WidthChanged = False If Length = 0 Then Return - Input = Input.ToLower(System.Globalization.CultureInfo.InvariantCulture) + Input = Input.ToLowerInvariant() Dim ExtraChars As Integer diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index 76806e79d1279c..bbfe3bf3bb1909 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -2703,7 +2703,7 @@ private string GetBaseTypeOutput(CodeTypeReference typeRef, bool preferBuiltInTy return "void"; } - string lowerCaseString = s.ToLower(CultureInfo.InvariantCulture).Trim(); + string lowerCaseString = s.ToLowerInvariant().Trim(); switch (lowerCaseString) { diff --git a/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs b/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs index 6744e198d8a6f5..8789e70b804f08 100644 --- a/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs +++ b/src/libraries/System.CodeDom/src/System/Collections/Specialized/FixedStringLookup.cs @@ -44,7 +44,7 @@ private static bool Contains(string[] array, string value, bool ignoreCase) { if (ignoreCase) { - searchChar = char.ToLower(value[pos], CultureInfo.InvariantCulture); + searchChar = char.ToLowerInvariant(value[pos]); } else { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs index 629b85a0d8d45e..58ba383de3e7bc 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesigntimeLicenseContext.cs @@ -99,7 +99,7 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) if (s != null) { - DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this); + DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpperInvariant(), this); break; } } @@ -140,7 +140,7 @@ public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) } if (s != null) { - DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this); + DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpperInvariant(), this); } } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs index 41cbde86f94a0e..4a3070bd9259d7 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs @@ -97,7 +97,7 @@ private ClientConfigPaths(string exePath, bool includeUserConfig) if (string.IsNullOrEmpty(namePrefix)) namePrefix = Validate(ProductName, limitSize: true); string applicationUriLower = !string.IsNullOrEmpty(ApplicationUri) - ? ApplicationUri.ToLower(CultureInfo.InvariantCulture) + ? ApplicationUri.ToLowerInvariant() : null; string hashSuffix = GetTypeAndHashSuffix(applicationUriLower); string part2 = !string.IsNullOrEmpty(namePrefix) && !string.IsNullOrEmpty(hashSuffix) diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs index 59bcf785131049..1d3de21976f0ab 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs @@ -1138,7 +1138,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ ((_itemLockedFlag & ConfigurationValueFlags.XmlParentInherited) == 0)) { dataToWrite = true; - writer?.WriteAttributeString(LockItemKey, true.ToString().ToLower(CultureInfo.InvariantCulture)); + writer?.WriteAttributeString(LockItemKey, true.ToString().ToLowerInvariant()); } } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IdnElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IdnElement.cs index b3439e9c03bf1c..82959a6a3aaf3e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IdnElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/IdnElement.cs @@ -50,11 +50,9 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { - string s = value as string; - if (s != null) + if (value is string s) { - s = s.ToLower(CultureInfo.InvariantCulture); - switch (s) + switch (s.ToLowerInvariant()) { case "all": return UriIdnScope.All; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs b/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs index d538b6ed476113..d914b982b279f6 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/AdapterUtil.Common.cs @@ -788,7 +788,7 @@ internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray) string columnName = columnNameArray[i]; if ((null != columnName) && (0 < columnName.Length)) { - columnName = columnName.ToLower(CultureInfo.InvariantCulture); + columnName = columnName.ToLowerInvariant(); int index; if (hash.TryGetValue(columnName, out index)) { @@ -814,7 +814,7 @@ internal static void BuildSchemaTableInfoTableNames(string[] columnNameArray) } else { - columnName = columnName.ToLower(CultureInfo.InvariantCulture); + columnName = columnName.ToLowerInvariant(); if (i != hash[columnName]) { GenerateUniqueName(hash, ref columnNameArray[i], i, 1); @@ -828,7 +828,7 @@ private static int GenerateUniqueName(Dictionary hash, ref string c for (; ; ++uniqueIndex) { string uniqueName = columnName + uniqueIndex.ToString(CultureInfo.InvariantCulture); - string lowerName = uniqueName.ToLower(CultureInfo.InvariantCulture); + string lowerName = uniqueName.ToLowerInvariant(); if (hash.TryAdd(lowerName, index)) { columnName = uniqueName; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs index 2a66db8d95cb33..53ed0493952f06 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs @@ -167,7 +167,7 @@ internal string ExpandKeyword(string keyword, string replacementValue) [Conditional("DEBUG")] static partial void DebugTraceKeyValuePair(string keyname, string keyvalue, Dictionary synonyms) { - Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower"); + Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower"); string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs index acf49eb6d0f4fb..59b1c5cd17dd84 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs @@ -484,7 +484,7 @@ internal string ExpandDataDirectories(ref string filename, ref int position) [System.Diagnostics.Conditional("DEBUG")] private static void DebugTraceKeyValuePair(string keyname, string keyvalue, Hashtable synonyms) { - Debug.Assert(keyname == keyname.ToLower(CultureInfo.InvariantCulture), "missing ToLower"); + Debug.Assert(keyname == keyname.ToLowerInvariant(), "missing ToLower"); string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); if ((KEY.Password != realkeyname) && (SYNONYM.Pwd != realkeyname)) @@ -505,7 +505,7 @@ private static string GetKeyName(StringBuilder buffer) { count--; // trailing whitespace } - return buffer.ToString(0, count).ToLower(CultureInfo.InvariantCulture); + return buffer.ToString(0, count).ToLowerInvariant(); } private static string GetKeyValue(StringBuilder buffer, bool trimWhitespace) @@ -795,7 +795,7 @@ private static Hashtable SplitConnectionString(string connectionString, Hashtabl CaptureCollection keyvalues = match.Groups[ValueIndex].Captures; foreach (Capture keypair in match.Groups[KeyIndex].Captures) { - string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLower(CultureInfo.InvariantCulture); + string keyname = (firstKey ? keypair.Value : keypair.Value.Replace("==", "=")).ToLowerInvariant(); string keyvalue = keyvalues[indexValue++].Value; if (0 < keyvalue.Length) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs index 994339d046ed47..7aea900b25b86b 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs @@ -275,7 +275,7 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect value = dataRow[backendtype, DataRowVersion.Default]; if (value is string) { - string backendtypename = ((string)value).ToLower(CultureInfo.InvariantCulture); + string backendtypename = ((string)value).ToLowerInvariant(); switch (backendtypename) { case "binary": diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs index 3a0dbd3b872298..d55018c3f989fa 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionString.cs @@ -448,7 +448,7 @@ private static void ValidateProvider(string progid) { throw ODB.InvalidProviderSpecified(); } - progid = progid.ToLower(CultureInfo.InvariantCulture); + progid = progid.ToLowerInvariant(); if (IsMSDASQL(progid)) { // fail msdasql even if not on the machine. diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs index bc92ee884f4dd8..258538540e00d3 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs @@ -566,7 +566,7 @@ public override StandardValuesCollection GetStandardValues(ITypeDescriptorContex if (DBSOURCETYPE_DATASOURCE_TDP == sourceType || DBSOURCETYPE_DATASOURCE_MDP == sourceType) { string progid = (string)row[column2]; - if (!OleDbConnectionString.IsMSDASQL(progid.ToLower(CultureInfo.InvariantCulture))) + if (!OleDbConnectionString.IsMSDASQL(progid.ToLowerInvariant())) { if (0 > providerNames.IndexOf(progid)) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 5ee968c3c07a02..38d750038223c7 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -1927,7 +1927,7 @@ private int IndexOf(Hashtable hash, string name) } // via case insensitive search, first match with lowest ordinal matches - string tmp = name.ToLower(CultureInfo.InvariantCulture); + string tmp = name.ToLowerInvariant(); index = hash[tmp]; // match via lowercase return ((null != index) ? (int)index : -1); } @@ -2027,7 +2027,7 @@ private void AppendSchemaInfo() string basecolumname = _metadata[i].baseColumnName; if (!ADP.IsEmpty(basecolumname)) { - basecolumname = basecolumname.ToLower(CultureInfo.InvariantCulture); + basecolumname = basecolumname.ToLowerInvariant(); if (!baseColumnNames.Contains(basecolumname)) { baseColumnNames[basecolumname] = i; diff --git a/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs b/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs index 78e3f3adb8a74e..c89a6065f13108 100644 --- a/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs +++ b/src/libraries/System.Data.OleDb/src/PropertyInfoSet.cs @@ -89,7 +89,7 @@ internal Dictionary GetValues() propertyInfo._vtype = propinfo.vtType; propertyInfo._supportedValues = propinfo.vValue; propertyInfo._description = propinfo.pwszDescription; - propertyInfo._lowercase = propinfo.pwszDescription.ToLower(CultureInfo.InvariantCulture); + propertyInfo._lowercase = propinfo.pwszDescription.ToLowerInvariant(); propertyInfo._type = PropertyInfoSet.FromVtType(propinfo.vtType); propertyLookup[propertyInfo._lowercase] = propertyInfo; diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs index 52df99b0ceb7e8..c075eff64fb77f 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollection.cs @@ -48,14 +48,14 @@ public InstanceData this[string instanceName] if (instanceName.Length == 0) instanceName = PerformanceCounterLib.SingleInstanceName; - string objectName = instanceName.ToLower(CultureInfo.InvariantCulture); + string objectName = instanceName.ToLowerInvariant(); return (InstanceData)Dictionary[objectName]; } } internal void Add(string instanceName, InstanceData value) { - string objectName = instanceName.ToLower(CultureInfo.InvariantCulture); + string objectName = instanceName.ToLowerInvariant(); Dictionary.Add(objectName, value); } @@ -64,7 +64,7 @@ public bool Contains(string instanceName) if (instanceName == null) throw new ArgumentNullException(nameof(instanceName)); - string objectName = instanceName.ToLower(CultureInfo.InvariantCulture); + string objectName = instanceName.ToLowerInvariant(); return Dictionary.Contains(objectName); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs index 8100b8dc25d9ab..dda9425d25cc66 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/InstanceDataCollectionCollection.cs @@ -26,7 +26,7 @@ public InstanceDataCollection this[string counterName] if (counterName == null) throw new ArgumentNullException(nameof(counterName)); - object objectName = counterName.ToLower(CultureInfo.InvariantCulture); + object objectName = counterName.ToLowerInvariant(); return (InstanceDataCollection)Dictionary[objectName]; } } @@ -46,7 +46,7 @@ public ICollection Values internal void Add(string counterName, InstanceDataCollection value) { - object objectName = counterName.ToLower(CultureInfo.InvariantCulture); + object objectName = counterName.ToLowerInvariant(); Dictionary.Add(objectName, value); } @@ -55,7 +55,7 @@ public bool Contains(string counterName) if (counterName == null) throw new ArgumentNullException(nameof(counterName)); - object objectName = counterName.ToLower(CultureInfo.InvariantCulture); + object objectName = counterName.ToLowerInvariant(); return Dictionary.Contains(objectName); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs index a25f7011c9b11f..f1637f4998c360 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs @@ -521,7 +521,7 @@ private void InitializeImpl() if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process) throw new InvalidOperationException(SR.InstanceLifetimeProcessforSingleInstance); - _sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime); + _sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLowerInvariant(), _counterName.ToLowerInvariant(), _instanceName.ToLowerInvariant(), _instanceLifetime); _initialized = true; } } @@ -593,7 +593,7 @@ public void RemoveInstance() throw new InvalidOperationException(SR.ReadOnlyRemoveInstance); Initialize(); - _sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime); + _sharedCounter.RemoveInstance(_instanceName.ToLowerInvariant(), _instanceLifetime); } } } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs index 27b67bb77270f3..4af24f4be7aae5 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs @@ -384,7 +384,7 @@ public static void Delete(string categoryName) CheckValidCategory(categoryName); string machineName = "."; - categoryName = categoryName.ToLower(CultureInfo.InvariantCulture); + categoryName = categoryName.ToLowerInvariant(); Mutex mutex = null; try diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs index e53adaf24c9914..14e20394fb6c19 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs @@ -172,7 +172,7 @@ protected static void LoadPropertyMappingTable(int mappingIndex, object[,] rawPr // It's probably a property that requires custom handling, such as IdentityClaim. if (fromLdap != null) { - string ldapAttributeLower = ldapAttribute.ToLower(CultureInfo.InvariantCulture); + string ldapAttributeLower = ldapAttribute.ToLowerInvariant(); if (mappingTableByLDAP[ldapAttributeLower] == null) mappingTableByLDAP[ldapAttributeLower] = new ArrayList(); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs index 45227a8f675c16..de8746cc1e2269 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs @@ -147,7 +147,7 @@ static SAMStoreCtx() // It's probably a property that requires custom handling, such as an IdentityClaim. if (fromWinNT != null) { - string winNTAttributeLower = winNTAttribute.ToLower(CultureInfo.InvariantCulture); + string winNTAttributeLower = winNTAttribute.ToLowerInvariant(); foreach (Hashtable propertyMappingTableByWinNT in byWinNTTables) { diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs index 940e66fd721295..92bf5b8cc52e2b 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs @@ -308,7 +308,7 @@ internal override void Load(Principal p) // Map each SAM attribute into the Principal in turn foreach (string samAttribute in samAttributes) { - ArrayList entries = (ArrayList)propertyMappingTableByWinNT[samAttribute.ToLower(CultureInfo.InvariantCulture)]; + ArrayList entries = (ArrayList)propertyMappingTableByWinNT[samAttribute.ToLowerInvariant()]; // If it's not in the table, it's not an SAM attribute we care about if (entries == null) diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs index 1953e634b15b49..5a9d65408f14cd 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryAttribute.cs @@ -276,7 +276,7 @@ public DirectoryAttribute this[string attributeName] throw new ArgumentNullException(nameof(attributeName)); } - object objectName = attributeName.ToLower(CultureInfo.InvariantCulture); + object objectName = attributeName.ToLowerInvariant(); return (DirectoryAttribute)InnerHashtable[objectName]; } } @@ -287,7 +287,7 @@ public DirectoryAttribute this[string attributeName] internal void Add(string name, DirectoryAttribute value) { - Dictionary.Add(name.ToLower(CultureInfo.InvariantCulture), value); + Dictionary.Add(name.ToLowerInvariant(), value); } public bool Contains(string attributeName) @@ -297,7 +297,7 @@ public bool Contains(string attributeName) throw new ArgumentNullException(nameof(attributeName)); } - object objectName = attributeName.ToLower(CultureInfo.InvariantCulture); + object objectName = attributeName.ToLowerInvariant(); return Dictionary.Contains(objectName); } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs index 7ab7cccf23bc35..6aa2c3c8158f36 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs @@ -24,7 +24,7 @@ public AttributeMetadata this[string name] { get { - string tempName = name.ToLower(CultureInfo.InvariantCulture); + string tempName = name.ToLowerInvariant(); if (Contains(tempName)) { return (AttributeMetadata)InnerHashtable[tempName]; @@ -40,7 +40,7 @@ public AttributeMetadata this[string name] public bool Contains(string attributeName) { - string tempName = attributeName.ToLower(CultureInfo.InvariantCulture); + string tempName = attributeName.ToLowerInvariant(); return Dictionary.Contains(tempName); } @@ -51,7 +51,7 @@ public void CopyTo(AttributeMetadata[] array, int index) private void Add(string name, AttributeMetadata value) { - Dictionary.Add(name.ToLower(CultureInfo.InvariantCulture), value); + Dictionary.Add(name.ToLowerInvariant(), value); AttributeNames.Add(name); Values.Add(value); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs index f4e0761267c10c..a211bbf5bc4330 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs @@ -1091,7 +1091,7 @@ private object GetValueFromCache(string propertyName, bool mustExist) InitializePropertiesFromSchemaContainer(); Debug.Assert(_propertyValuesFromServer != null); - ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLower(CultureInfo.InvariantCulture)]; + ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLowerInvariant()]; Debug.Assert(values != null); if (values.Count < 1 && mustExist) @@ -1116,7 +1116,7 @@ private ICollection GetValuesFromCache(string propertyName) InitializePropertiesFromSchemaContainer(); Debug.Assert(_propertyValuesFromServer != null); - ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLower(CultureInfo.InvariantCulture)]; + ArrayList values = (ArrayList)_propertyValuesFromServer[propertyName.ToLowerInvariant()]; Debug.Assert(values != null); return values; diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs index 2671fb234fd58f..e35ece7285cfe1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs @@ -704,7 +704,7 @@ private void GetSites() propertyList.Add(propertyName); Hashtable values = Utils.GetValuesWithRangeRetrieval(cachedEntry, "(objectClass=*)", propertyList, SearchScope.Base); - ArrayList siteLists = (ArrayList)values[propertyName.ToLower(CultureInfo.InvariantCulture)]; + ArrayList siteLists = (ArrayList)values[propertyName.ToLowerInvariant()]; // somehow no site list if (siteLists == null) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs index e4cf6b58a753f6..286cd8489d0174 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs @@ -360,7 +360,7 @@ private void GetLinks() propertyList.Add(propertyName); Hashtable values = Utils.GetValuesWithRangeRetrieval(cachedEntry, "(objectClass=*)", propertyList, SearchScope.Base); - ArrayList siteLinkLists = (ArrayList)values[propertyName.ToLower(CultureInfo.InvariantCulture)]; + ArrayList siteLinkLists = (ArrayList)values[propertyName.ToLowerInvariant()]; // somehow no site link list if (siteLinkLists == null) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs index 6e3d8bc3dd1afd..2d9f940a292ad3 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs @@ -260,7 +260,7 @@ internal ArrayList GetPartitions() throw ExceptionHelper.GetExceptionFromCOMException(context, e); } - ArrayList readOnlyPartitions = (ArrayList)values[PropertyManager.HasPartialReplicaNCs.ToLower(CultureInfo.InvariantCulture)]; + ArrayList readOnlyPartitions = (ArrayList)values[PropertyManager.HasPartialReplicaNCs.ToLowerInvariant()]; Debug.Assert(readOnlyPartitions != null); foreach (string readOnlyPartition in readOnlyPartitions) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs index d4b406a603d55e..f372b72fe4d270 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs @@ -159,7 +159,7 @@ private static Hashtable DnsGetDcWrapper(string domainName, string siteName, lon try { dcDnsHostName = Marshal.PtrToStringUni(dcDnsHostNamePtr); - string key = dcDnsHostName.ToLower(CultureInfo.InvariantCulture); + string key = dcDnsHostName.ToLowerInvariant(); if (!domainControllers.Contains(key)) { @@ -254,7 +254,7 @@ private static Hashtable DnsQueryWrapper(string domainName, string siteName, lon DnsRecord dnsRecord = new DnsRecord(); Marshal.PtrToStructure(currentDnsRecord, dnsRecord); string targetName = dnsRecord.data.targetName; - string key = targetName.ToLower(CultureInfo.InvariantCulture); + string key = targetName.ToLowerInvariant(); if (!domainControllers.Contains(key)) { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index 62ef80c1f65933..e5cd5a99abbf6a 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -1107,7 +1107,7 @@ internal static Hashtable GetValuesWithRangeRetrieval(DirectoryEntry searchRootE foreach (string propertyName in propertiesWithoutRangeRetrieval) { // need to convert to lower case since S.DS returns property names in all lower case - string lowerCasePropertyName = propertyName.ToLower(CultureInfo.InvariantCulture); + string lowerCasePropertyName = propertyName.ToLowerInvariant(); propertyNamesWithoutRangeInfo.Add(lowerCasePropertyName); results.Add(lowerCasePropertyName, new ArrayList()); // add to the seachers's propertiesToLoad @@ -1119,7 +1119,7 @@ internal static Hashtable GetValuesWithRangeRetrieval(DirectoryEntry searchRootE foreach (string propertyName in propertiesWithRangeRetrieval) { // need to convert to lower case since S.DS returns property names in all lower case - string lowerCasePropertyName = propertyName.ToLower(CultureInfo.InvariantCulture); + string lowerCasePropertyName = propertyName.ToLowerInvariant(); propertiesStillToLoad.Add(lowerCasePropertyName); results.Add(lowerCasePropertyName, new ArrayList()); } @@ -1131,7 +1131,7 @@ internal static Hashtable GetValuesWithRangeRetrieval(DirectoryEntry searchRootE string propertyToLoad = propertyName + ";range=" + rangeStart + "-*"; searcher.PropertiesToLoad.Add(propertyToLoad); // need to convert to lower case since S.DS returns property names in all lower case - propertyNamesWithRangeInfo.Add(propertyName.ToLower(CultureInfo.InvariantCulture), propertyToLoad); + propertyNamesWithRangeInfo.Add(propertyName.ToLowerInvariant(), propertyToLoad); } //clear for the nezxt round @@ -1294,8 +1294,8 @@ internal static ArrayList GetReplicaList(DirectoryContext context, string partit } // extract the property values - ArrayList replicaLocations = (ArrayList)values[PropertyManager.MsDSNCReplicaLocations.ToLower(CultureInfo.InvariantCulture)]; - ArrayList roReplicaLocations = (ArrayList)values[PropertyManager.MsDSNCROReplicaLocations.ToLower(CultureInfo.InvariantCulture)]; + ArrayList replicaLocations = (ArrayList)values[PropertyManager.MsDSNCReplicaLocations.ToLowerInvariant()]; + ArrayList roReplicaLocations = (ArrayList)values[PropertyManager.MsDSNCROReplicaLocations.ToLowerInvariant()]; Debug.Assert(replicaLocations != null); if (replicaLocations.Count == 0) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index af515111e827d0..7f093c6f94ffaa 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -999,7 +999,7 @@ public void RefreshCache(string[] propertyNames) { if (propertyNames[i] != null) { - string name = propertyNames[i].ToLower(CultureInfo.InvariantCulture); + string name = propertyNames[i].ToLowerInvariant(); _propertyCollection.valueTable.Remove(name); // also need to consider the range retrieval case diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs index 8990b5b492cc7d..5855d93d7bf37f 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs @@ -34,7 +34,7 @@ public PropertyValueCollection this[string propertyName] if (propertyName == null) throw new ArgumentNullException(nameof(propertyName)); - string name = propertyName.ToLower(CultureInfo.InvariantCulture); + string name = propertyName.ToLowerInvariant(); if (valueTable.Contains(name)) return (PropertyValueCollection)valueTable[name]; else diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs index 7ed4132e113745..a2ec31720a5166 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs @@ -23,7 +23,7 @@ public ResultPropertyValueCollection this[string name] { get { - object objectName = name.ToLower(CultureInfo.InvariantCulture); + object objectName = name.ToLowerInvariant(); if (Contains((string)objectName)) { return (ResultPropertyValueCollection)InnerHashtable[objectName]; @@ -41,12 +41,12 @@ public ResultPropertyValueCollection this[string name] internal void Add(string name, ResultPropertyValueCollection value) { - Dictionary.Add(name.ToLower(CultureInfo.InvariantCulture), value); + Dictionary.Add(name.ToLowerInvariant(), value); } public bool Contains(string propertyName) { - object objectName = propertyName.ToLower(CultureInfo.InvariantCulture); + object objectName = propertyName.ToLowerInvariant(); return Dictionary.Contains(objectName); } diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index 9e93670a645ccd..62797f9dbd3e5d 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -3063,7 +3063,7 @@ protected internal override void ParseQuery(string query) //Find "group within" clause keyword = "group within "; - if ((q.Length >= keyword.Length) && ((i = q.ToLower(CultureInfo.InvariantCulture).IndexOf(keyword, StringComparison.Ordinal)) != -1)) //found + if ((q.Length >= keyword.Length) && ((i = q.ToLowerInvariant().IndexOf(keyword, StringComparison.Ordinal)) != -1)) //found { //Separate the part of the string before this - that should be the "where" clause w = q.Substring(0, i).Trim(); diff --git a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs index 4813123d863d51..927a35474b61fc 100644 --- a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs +++ b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs @@ -825,7 +825,7 @@ private string ResolveCollision(string inString, bool bCheckthisFirst) if (strTemp.Length > 0) { - string strFirstChar = strTemp.Substring(0, 1).ToUpper(CultureInfo.InvariantCulture); + string strFirstChar = strTemp.Substring(0, 1).ToUpperInvariant(); strTemp = strFirstChar + strTemp.Substring(1, strTemp.Length - 1); } @@ -846,7 +846,7 @@ private void ProcessNamespaceAndClassName() { strNs = OriginalNamespace; strNs = strNs.Replace('\\', '.'); - strNs = strNs.ToUpper(CultureInfo.InvariantCulture); + strNs = strNs.ToUpperInvariant(); } else { @@ -1141,7 +1141,7 @@ private CodeTypeDeclaration GenerateSystemPropertiesClass() strPropName[j - i] = strPropTemp[j]; } - cmp.Name = (new string(strPropName)).ToUpper(CultureInfo.InvariantCulture); + cmp.Name = (new string(strPropName)).ToUpperInvariant(); cmp.Attributes = MemberAttributes.Public | MemberAttributes.Final; cmp.Type = ConvertCIMType(prop.Type, prop.IsArray); @@ -5006,7 +5006,7 @@ private static int ConvertBitMapValueToInt32(string bitMap) string strTemp = "0x"; int ret = 0; - if (bitMap.StartsWith(strTemp, StringComparison.Ordinal) || bitMap.StartsWith(strTemp.ToUpper(CultureInfo.InvariantCulture), StringComparison.Ordinal)) + if (bitMap.StartsWith(strTemp, StringComparison.Ordinal) || bitMap.StartsWith(strTemp.ToUpperInvariant(), StringComparison.Ordinal)) { strTemp = string.Empty; char[] arrString = bitMap.ToCharArray(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index b1d9fa0feceb50..d1b72728c21303 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -179,7 +179,7 @@ public bool KeepAlive } else { - header = header.ToLower(CultureInfo.InvariantCulture); + header = header.ToLowerInvariant(); _keepAlive = header.IndexOf("close", StringComparison.OrdinalIgnoreCase) < 0 || header.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/HeaderCollection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/HeaderCollection.cs index 55476e42d4a37b..c2ec43e1ae6ace 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/HeaderCollection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/HeaderCollection.cs @@ -154,11 +154,11 @@ public override void Set(string name, string value) if (id == MailHeaderID.ContentType && _part != null) { - _part.ContentType.Set(value.ToLower(CultureInfo.InvariantCulture), this); + _part.ContentType.Set(value.ToLowerInvariant(), this); } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { - ((MimePart)_part).ContentDisposition.Set(value.ToLower(CultureInfo.InvariantCulture), this); + ((MimePart)_part).ContentDisposition.Set(value.ToLowerInvariant(), this); } else { @@ -197,11 +197,11 @@ public override void Add(string name, string value) if (id == MailHeaderID.ContentType && _part != null) { - _part.ContentType.Set(value.ToLower(CultureInfo.InvariantCulture), this); + _part.ContentType.Set(value.ToLowerInvariant(), this); } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { - ((MimePart)_part).ContentDisposition.Set(value.ToLower(CultureInfo.InvariantCulture), this); + ((MimePart)_part).ContentDisposition.Set(value.ToLowerInvariant(), this); } else { 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 b5f93ae9a7f730..96ae395ac0c4d8 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 @@ -37,7 +37,7 @@ internal MimeMultiPartType MimeMultiPartType private void SetType(MimeMultiPartType type) { - ContentType.MediaType = "multipart" + "/" + type.ToString().ToLower(CultureInfo.InvariantCulture); + ContentType.MediaType = "multipart" + "/" + type.ToString().ToLowerInvariant(); ContentType.Boundary = GetNextBoundary(); } 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 c7478f2e03c0fd..65aebf79a995ab 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -98,7 +98,7 @@ internal bool ShouldParseForResponseUri internal static FtpMethodInfo GetMethodInfo(string method) { - method = method.ToUpper(CultureInfo.InvariantCulture); + method = method.ToUpperInvariant(); foreach (FtpMethodInfo methodInfo in s_knownMethodInfo) if (method == methodInfo.Method) return methodInfo; diff --git a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs index 31d33e733d8b68..2cbd24a9ef8c54 100644 --- a/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs +++ b/src/libraries/System.Net.WebClient/src/System/Net/WebClient.cs @@ -1110,7 +1110,7 @@ private string GetStringUsingEncoding(WebRequest request, byte[] data) if (contentType != null) { - contentType = contentType.ToLower(CultureInfo.InvariantCulture); + contentType = contentType.ToLowerInvariant(); string[] parsedList = contentType.Split(s_parseContentTypeSeparators); bool nextItem = false; foreach (string item in parsedList) diff --git a/src/libraries/System.Private.CoreLib/src/System/Char.cs b/src/libraries/System.Private.CoreLib/src/System/Char.cs index 7b032197f00e7e..02e49c90420da2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Char.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Char.cs @@ -355,7 +355,7 @@ public static char ToUpper(char c) // Converts a character to upper-case for invariant culture. public static char ToUpperInvariant(char c) { - return CultureInfo.InvariantCulture.TextInfo.ToUpper(c); + return TextInfo.Invariant.ToUpper(c); } /*===================================ToLower==================================== @@ -384,7 +384,7 @@ public static char ToLower(char c) // Converts a character to lower-case for invariant culture. public static char ToLowerInvariant(char c) { - return CultureInfo.InvariantCulture.TextInfo.ToLower(c); + return TextInfo.Invariant.ToLower(c); } // 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 348c05c1bb04e7..ea5a3d68e6a4ed 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -45,9 +45,7 @@ private enum Tristate : byte private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized; // Invariant text info - internal static TextInfo Invariant => s_invariant ??= new TextInfo(CultureData.Invariant); - - private static volatile TextInfo? s_invariant; + internal static readonly TextInfo Invariant = new TextInfo(CultureData.Invariant); internal TextInfo(CultureData cultureData) { diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs index 8e51249f5e50b7..a71ecc4deb0eba 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -1690,7 +1690,7 @@ public string ToLower(CultureInfo? culture) // Creates a copy of this string in lower case based on invariant culture. public string ToLowerInvariant() { - return CultureInfo.InvariantCulture.TextInfo.ToLower(this); + return TextInfo.Invariant.ToLower(this); } public string ToUpper() => ToUpper(null); @@ -1705,7 +1705,7 @@ public string ToUpper(CultureInfo? culture) // Creates a copy of this string in upper case based on invariant culture. public string ToUpperInvariant() { - return CultureInfo.InvariantCulture.TextInfo.ToUpper(this); + return TextInfo.Invariant.ToUpper(this); } // Trims the whitespace from both ends of the string. Whitespace is defined by diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs index 1283ea32cdbd17..d121b75c9ef52d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs @@ -267,7 +267,7 @@ internal static string XdrCanonizeUri(string uri, XmlNameTable nameTable, Schema if (convert) { - canonicalUri = nameTable.Add(string.Concat(uri.AsSpan(0, offset), CultureInfo.InvariantCulture.TextInfo.ToUpper(uri.Substring(offset, uri.Length - offset)))); + canonicalUri = nameTable.Add(string.Concat(uri.AsSpan(0, offset), uri.Substring(offset, uri.Length - offset).ToUpperInvariant())); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs index 5fb65054c91b91..cdbbf07e57336b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs @@ -34,7 +34,7 @@ public static string MakePascal(string identifier) identifier = MakeValid(identifier); if (identifier.Length <= 2) { - return CultureInfo.InvariantCulture.TextInfo.ToUpper(identifier); + return identifier.ToUpperInvariant(); } else if (char.IsLower(identifier[0])) { @@ -55,11 +55,11 @@ public static string MakeCamel(string identifier) identifier = MakeValid(identifier); if (identifier.Length <= 2) { - return CultureInfo.InvariantCulture.TextInfo.ToLower(identifier); + return identifier.ToLowerInvariant(); } else if (char.IsUpper(identifier[0])) { - char lower = char.ToLower(identifier[0]); + char lower = char.ToLowerInvariant(identifier[0]); return string.Concat(MemoryMarshal.CreateReadOnlySpan(ref lower, 1), identifier.AsSpan(1)); } else diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs index e7a2bf579e005b..ec008d25acf96a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/RuntimeType.Mono.cs @@ -263,7 +263,7 @@ private static void FilterHelper( { if ((bindingFlags & BindingFlags.IgnoreCase) != 0) { - name = name.ToLower(CultureInfo.InvariantCulture); + name = name.ToLowerInvariant(); ignoreCase = true; listType = MemberListType.CaseInsensitive; } @@ -323,7 +323,7 @@ private static bool FilterApplyBase( { #region Preconditions Contract.Requires(memberInfo != null); - Contract.Requires(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLower(CultureInfo.InvariantCulture).Equals(name))); + Contract.Requires(name == null || (bindingFlags & BindingFlags.IgnoreCase) == 0 || (name.ToLowerInvariant().Equals(name))); #endregion #region Filter by Public & Private From 942e8adb8e234fc0592f86d8e501aeb23059e8f2 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Fri, 7 Feb 2020 16:27:19 -0800 Subject: [PATCH 2/9] Fix some uses of culture-aware ToUpper / ToLower to use invariant culture --- .../System.Net.Requests/src/System/Net/HttpWebResponse.cs | 2 +- src/libraries/System.Private.Uri/src/System/UriScheme.cs | 2 +- .../src/System/Xml/Xsl/Runtime/XmlCollation.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs index d0f21195634572..57bfee634c96c7 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs @@ -272,7 +272,7 @@ public string CharacterSet _characterSet = string.Empty; //first string is the media type - string srchString = contentType.ToLower(); + string srchString = contentType.ToLowerInvariant(); //media subtypes of text type has a default as specified by rfc 2616 if (srchString.Trim().StartsWith("text/", StringComparison.Ordinal)) diff --git a/src/libraries/System.Private.Uri/src/System/UriScheme.cs b/src/libraries/System.Private.Uri/src/System/UriScheme.cs index 13005c2dc6a0ff..64f8abc6995fec 100644 --- a/src/libraries/System.Private.Uri/src/System/UriScheme.cs +++ b/src/libraries/System.Private.Uri/src/System/UriScheme.cs @@ -159,7 +159,7 @@ public static void Register(UriParser uriParser, string schemeName, int defaultP if ((defaultPort >= 0xFFFF || defaultPort < 0) && defaultPort != -1) throw new ArgumentOutOfRangeException(nameof(defaultPort)); - schemeName = schemeName.ToLower(); + schemeName = schemeName.ToLowerInvariant(); FetchSyntax(uriParser, schemeName, defaultPort); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs index 06a768a75d6168..8158fb9620c7fe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs @@ -227,8 +227,8 @@ internal static XmlCollation Create(string collationLiteral, bool throwOnError) throw new XslTransformException(SR.Coll_BadOptFormat, option); } - string optionName = pair[0].ToUpper(); - string optionValue = pair[1].ToUpper(); + string optionName = pair[0].ToUpperInvariant(); + string optionValue = pair[1].ToUpperInvariant(); if (optionName == "SORT") { From 2c7accbe36f8fa45a9c1e59e4f67b815c8b5e5de Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Fri, 7 Feb 2020 16:38:10 -0800 Subject: [PATCH 3/9] Replace Trim().Length with IsNullOrWhiteSpace --- .../System/ComponentModel/DataAnnotations/RequiredAttribute.cs | 2 +- .../System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs | 2 +- src/libraries/System.Data.OleDb/src/OleDbConnection.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs index e9760e480281f9..382947cf252cf0 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RequiredAttribute.cs @@ -45,7 +45,7 @@ public override bool IsValid(object value) } // only check string length if empty strings are not allowed - return AllowEmptyStrings || !(value is string stringValue) || stringValue.Trim().Length != 0; + return AllowEmptyStrings || !(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue); } } } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs index 4d85b611d786e5..e3aff7929cb945 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs @@ -940,7 +940,7 @@ internal void Open_ChangeDatabase(string value) CheckState(ADP.ChangeDatabase); // Database name must not be null, empty or whitspace - if ((null == value) || (0 == value.Trim().Length)) + if (string.IsNullOrWhiteSpace(value)) { // MDAC 62679 throw ADP.EmptyDatabaseName(); } diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 3a9a17c7e897f1..407e070e3ea761 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -319,7 +319,7 @@ internal int QuotedIdentifierCase() public override void ChangeDatabase(string value) { CheckStateOpen(ADP.ChangeDatabase); - if ((null == value) || (0 == value.Trim().Length)) + if (string.IsNullOrWhiteSpace(value)) { throw ADP.EmptyDatabaseName(); } From 693e0e357078ad8c4e8bff176427341cffcd2c53 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Fri, 7 Feb 2020 17:32:19 -0800 Subject: [PATCH 4/9] Use ordinal StartsWith / EndsWith where appropriate - Also uses Starts/EndsWith(char) if available --- .../Microsoft.XmlSerializer.Generator/src/Sgen.cs | 2 +- .../src/System/ComponentModel/SyntaxCheck.cs | 4 ++-- .../src/System/Data/DataTable.cs | 4 ++-- .../src/System/Data/XMLSchema.cs | 2 +- .../src/System/Diagnostics/Process.Windows.cs | 2 +- .../System/Diagnostics/ProcessManager.Windows.cs | 2 +- .../DirectoryServices/ActiveDirectory/Utils.cs | 4 ++-- .../src/System/IO/Ports/SerialPort.FreeBSD.cs | 4 ++-- .../src/System/IO/Ports/SerialPort.Linux.cs | 14 +++++++------- .../src/System/IO/Ports/SerialPort.OSX.cs | 4 ++-- .../Http/Headers/ContentDispositionHeaderValue.cs | 4 ++-- .../src/System/Net/Http/MultipartContent.cs | 4 ++-- .../System/Net/Managed/HttpEndPointListener.cs | 4 ++-- .../Net/Managed/HttpListenerRequest.Managed.cs | 2 +- .../src/System/Net/Managed/ListenerPrefix.cs | 2 +- .../src/System/Net/Mime/SmtpDateTime.cs | 4 ++-- .../StringParsingHelpers.Addresses.cs | 4 ++-- .../src/System/Net/Cookie.cs | 2 +- .../src/System/Net/CookieContainer.cs | 2 +- .../src/System/Net/WebRequest.cs | 2 +- .../src/System/AppContextConfigHelper.cs | 15 +++++++++------ .../src/System/Diagnostics/DebugProvider.cs | 2 +- .../Tracing/TraceLogging/EventSourceActivity.cs | 2 +- .../Serialization/CollectionDataContract.cs | 2 +- .../Xml/Serialization/XmlSerializationReader.cs | 2 +- .../Serialization/XmlSerializationWriterILGen.cs | 2 +- .../General/TypeExtensions.netstandard.cs | 2 +- .../Resources/WindowsRuntimeResourceManager.cs | 2 +- .../Text/Json/Serialization/JsonClassInfo.cs | 6 +++--- 29 files changed, 55 insertions(+), 52 deletions(-) diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index 58b582f9688e92..8a08a19efdce71 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -309,7 +309,7 @@ private void GenerateFile(List typeNames, string assemblyName, bool prox //However when a path ending with backslash, if followed by double quote, it becomes an escapte sequence //e.g. "obj\Debug\netcoreapp2.0\", it will be converted as obj\Debug\netcoreapp2.0", which is not valid and not exist //We need remove the ending quote for this situation - if (!outputDirectory.EndsWith("\"") || !Directory.Exists(outputDirectory = outputDirectory.Remove(outputDirectory.Length - 1))) + if (!outputDirectory.EndsWith("\"", StringComparison.Ordinal) || !Directory.Exists(outputDirectory = outputDirectory.Remove(outputDirectory.Length - 1))) { throw new ArgumentException(SR.Format(SR.ErrDirectoryNotExists, outputDirectory)); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs index c0ed8f443e495f..f2e4bce1ab01bb 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/SyntaxCheck.cs @@ -36,12 +36,12 @@ public static bool CheckPath(string value) if (value == null) return false; - value = value.Trim(); + value = value.TrimStart(); if (value.Equals(string.Empty)) return false; // Path names should start with "\\" - return value.StartsWith("\\\\"); + return value.StartsWith("\\\\", StringComparison.Ordinal); } /// diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index a5665e65a67500..7f7e45b7ea1122 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -3711,9 +3711,9 @@ internal IndexField[] ParseSortString(string sortString) } // handle brackets. - if (current.StartsWith("[", StringComparison.Ordinal)) + if (current.StartsWith('[')) { - if (current.EndsWith("]", StringComparison.Ordinal)) + if (current.EndsWith(']')) { current = current.Substring(1, current.Length - 2); } diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index 726c377f61e150..fd95e93c6cf20c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -1161,7 +1161,7 @@ internal DataColumn FindField(DataTable table, string field) bool attribute = false; string colName = field; - if (field.StartsWith("@", StringComparison.Ordinal)) + if (field.StartsWith('@')) { attribute = true; colName = field.Substring(1); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs index ec8601c1217bc3..29a5e527cc0783 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs @@ -676,7 +676,7 @@ private static StringBuilder BuildCommandLine(string executableFileName, string // is the file to execute). StringBuilder commandLine = new StringBuilder(); string fileName = executableFileName.Trim(); - bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal)); + bool fileNameIsQuoted = (fileName.StartsWith('\"') && fileName.EndsWith('\"')); if (!fileNameIsQuoted) { commandLine.Append("\""); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs index bd40aea2593fb9..6aa2ebc6979335 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs @@ -125,7 +125,7 @@ public static ProcessModuleCollection GetModules(int processId) private static bool IsRemoteMachineCore(string machineName) { - ReadOnlySpan baseName = machineName.AsSpan(machineName.StartsWith("\\", StringComparison.Ordinal) ? 2 : 0); + ReadOnlySpan baseName = machineName.AsSpan(machineName.StartsWith('\\') ? 2 : 0); return !baseName.Equals(".", StringComparison.Ordinal) && !baseName.Equals(Interop.Kernel32.GetComputerName(), StringComparison.OrdinalIgnoreCase); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs index e5cd5a99abbf6a..7d9f6da826ed33 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs @@ -1935,10 +1935,10 @@ internal static string SplitServerNameAndPortNumber(string serverName, out strin } //extract IPv6 port number if any - bool isBrace = serverName.StartsWith("["); + bool isBrace = serverName.StartsWith("[", StringComparison.Ordinal); if (isBrace == true) { - if (serverName.EndsWith("]")) + if (serverName.EndsWith("]", StringComparison.Ordinal)) { //[IPv6] serverName = serverName.Substring(1, serverName.Length - 2); //2 for [] diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.FreeBSD.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.FreeBSD.cs index c56f59cfd54b1a..47ac11438725e7 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.FreeBSD.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.FreeBSD.cs @@ -17,7 +17,7 @@ public static string[] GetPortNames() foreach (string name in Directory.GetFiles("/dev", "ttyd*")) { - if (!name.EndsWith(".init") && !name.EndsWith(".lock")) + if (!name.EndsWith(".init", StringComparison.Ordinal) && !name.EndsWith(".lock", StringComparison.Ordinal)) { ports.Add(name); } @@ -25,7 +25,7 @@ public static string[] GetPortNames() foreach (string name in Directory.GetFiles("/dev", "cuau*")) { - if (!name.EndsWith(".init") && !name.EndsWith(".lock")) + if (!name.EndsWith(".init", StringComparison.Ordinal) && !name.EndsWith(".lock", StringComparison.Ordinal)) { ports.Add(name); } diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Linux.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Linux.cs index fa9ba5da196eb0..3f2eadfd7373f3 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Linux.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.Linux.cs @@ -32,8 +32,8 @@ public static string[] GetPortNames() // by checking for presence of device/id or device/of_node // checking for that for non-ttyS entries is incorrect as some uart // devices are incorrectly filtered out - bool isTtyS = entry.Name.StartsWith("ttyS"); - bool isTtyGS = !isTtyS && entry.Name.StartsWith("ttyGS"); + bool isTtyS = entry.Name.StartsWith("ttyS", StringComparison.Ordinal); + bool isTtyGS = !isTtyS && entry.Name.StartsWith("ttyGS", StringComparison.Ordinal); if ((isTtyS && (File.Exists(entry.FullName + "/device/id") || Directory.Exists(entry.FullName + "/device/of_node"))) || @@ -58,11 +58,11 @@ public static string[] GetPortNames() var ports = new List(); foreach (var portName in Directory.EnumerateFiles(devDir, "tty*")) { - if (portName.StartsWith("/dev/ttyS") || - portName.StartsWith("/dev/ttyUSB") || - portName.StartsWith("/dev/ttyACM") || - portName.StartsWith("/dev/ttyAMA") || - portName.StartsWith("/dev/ttymxc")) + if (portName.StartsWith("/dev/ttyS", StringComparison.Ordinal) || + portName.StartsWith("/dev/ttyUSB", StringComparison.Ordinal) || + portName.StartsWith("/dev/ttyACM", StringComparison.Ordinal) || + portName.StartsWith("/dev/ttyAMA", StringComparison.Ordinal) || + portName.StartsWith("/dev/ttymxc", StringComparison.Ordinal)) { ports.Add(portName); } diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.OSX.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.OSX.cs index dcd2a47eb1c264..be1f9d8796a10d 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.OSX.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialPort.OSX.cs @@ -19,7 +19,7 @@ public static string[] GetPortNames() { // GetFiles can return unexpected results because of 8.3 matching. // Like /dev/tty - if (name.StartsWith("/dev/tty.")) + if (name.StartsWith("/dev/tty.", StringComparison.Ordinal)) { ports.Add(name); } @@ -27,7 +27,7 @@ public static string[] GetPortNames() foreach (string name in Directory.GetFiles("/dev", "cu.*")) { - if (name.StartsWith("/dev/cu.")) + if (name.StartsWith("/dev/cu.", StringComparison.Ordinal)) { ports.Add(name); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs index 29cb3d50cac727..a999f77fab4a65 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/ContentDispositionHeaderValue.cs @@ -367,7 +367,7 @@ private string GetName(string parameter) { string result; // filename*=utf-8'lang'%7FMyString - if (parameter.EndsWith("*", StringComparison.Ordinal)) + if (parameter.EndsWith('*')) { if (TryDecode5987(nameParameter.Value, out result)) { @@ -403,7 +403,7 @@ private void SetName(string parameter, string value) else { string processedValue = string.Empty; - if (parameter.EndsWith("*", StringComparison.Ordinal)) + if (parameter.EndsWith('*')) { processedValue = HeaderUtilities.Encode5987(value); } diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs index 0f832a73f7c246..d1f54dbe791e5b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/MultipartContent.cs @@ -53,7 +53,7 @@ public MultipartContent(string subtype, string boundary) _boundary = boundary; string quotedBoundary = boundary; - if (!quotedBoundary.StartsWith("\"", StringComparison.Ordinal)) + if (!quotedBoundary.StartsWith('\"')) { quotedBoundary = "\"" + quotedBoundary + "\""; } @@ -84,7 +84,7 @@ private static void ValidateBoundary(string boundary) SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70)); } // Cannot end with space. - if (boundary.EndsWith(" ", StringComparison.Ordinal)) + if (boundary.EndsWith(' ')) { throw new ArgumentException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs index 9baf0a66e87770..96847d65272a72 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs @@ -194,7 +194,7 @@ private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) if (p.Host != host || p.Port != port) continue; - if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath)) + if (path.StartsWith(ppath, StringComparison.Ordinal) || pathSlash.StartsWith(ppath, StringComparison.Ordinal)) { bestLength = ppath.Length; bestMatch = localPrefixes[p]; @@ -241,7 +241,7 @@ private HttpListener MatchFromList(string host, string path, List ParseIPv4GatewayAddressesFromR // Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT foreach (string line in fileLines) { - if (line.StartsWith(interfaceName)) + if (line.StartsWith(interfaceName, StringComparison.Ordinal)) { StringParser parser = new StringParser(line, '\t', skipEmpty: true); parser.MoveNext(); @@ -57,7 +57,7 @@ internal static void ParseIPv6GatewayAddressesFromRouteFile(List 9 && token[4] != "00000000000000000000000000000000") diff --git a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs index 316617ebfdd7ef..3eac02c7dab172 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/Cookie.cs @@ -510,7 +510,7 @@ internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDoma else { // Check current path (implicit/explicit) against given URI. - if (!path.StartsWith(CookieParser.CheckQuoted(m_path))) + if (!path.StartsWith(CookieParser.CheckQuoted(m_path), StringComparison.Ordinal)) { if (shouldThrow) { diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index 4c73a94b3a7709..3e69c3fb5bc77a 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -885,7 +885,7 @@ private void BuildCookieCollectionFromDomainMatches(Uri uri, bool isSecure, int while (e.MoveNext()) { string path = (string)e.Key; - if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path))) + if (uri.AbsolutePath.StartsWith(CookieParser.CheckQuoted(path), StringComparison.Ordinal)) { CookieCollection cc = (CookieCollection)e.Value; cc.TimeStamp(CookieCollection.Stamp.Set); diff --git a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs index fee9c547e52c12..976b6ef53c9864 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/WebRequest.cs @@ -268,7 +268,7 @@ public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) // Special case for when a partial host matching is requested, drop the added trailing slash // IE: http://host could match host or host.domain - if (!prefix.EndsWith("/", StringComparison.Ordinal) + if (!prefix.EndsWith('/') && tempUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped) .Equals("/")) { diff --git a/src/libraries/System.Private.CoreLib/src/System/AppContextConfigHelper.cs b/src/libraries/System.Private.CoreLib/src/System/AppContextConfigHelper.cs index 466e1636a01784..a5507634800aff 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppContextConfigHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppContextConfigHelper.cs @@ -17,13 +17,16 @@ internal static int GetInt32Config(string configName, int defaultValue, bool all switch (config) { case string str: - if (str.StartsWith("0x")) - { - result = Convert.ToInt32(str, 16); - } - else if (str.StartsWith("0")) + if (str.StartsWith('0')) { - result = Convert.ToInt32(str, 8); + if (str.Length >= 2 && str[1] == 'x') + { + result = Convert.ToInt32(str, 16); + } + else + { + result = Convert.ToInt32(str, 8); + } } else { diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs index cf4dfe1effdb81..65cbe8e16c881f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/DebugProvider.cs @@ -52,7 +52,7 @@ public virtual void Write(string? message) _needIndent = false; } WriteCore(message); - if (message.EndsWith(Environment.NewLineConst)) + if (message.EndsWith(Environment.NewLineConst, StringComparison.Ordinal)) { _needIndent = true; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs index 25c8563346af80..b68bac3e546479 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs @@ -282,7 +282,7 @@ private void Stop(string? eventName, ref T data) if (eventName == null) { eventName = this.eventName; - if (eventName.EndsWith("Start")) + if (eventName.EndsWith("Start", StringComparison.Ordinal)) eventName = eventName.Substring(0, eventName.Length - 5); eventName += "Stop"; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs index f82d05268fe4af..6fc5bec9af0ffa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs @@ -1298,7 +1298,7 @@ private static void GetCollectionMethods(Type type, Type interfaceType, Type[] a getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { - Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); + Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable", StringComparison.Ordinal)).FirstOrDefault(); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); 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 b50d640e131c2a..1b80225df360f3 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 @@ -1421,7 +1421,7 @@ protected bool ReadReference(out string fixupReference) if (!_soap12) { // soap 1.1 href starts with '#'; soap 1.2 ref does not - if (!href.StartsWith("#", StringComparison.Ordinal)) throw new InvalidOperationException(SR.Format(SR.XmlMissingHref, href)); + if (!href.StartsWith('#')) throw new InvalidOperationException(SR.Format(SR.XmlMissingHref, href)); fixupReference = href.Substring(1); } else diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index 10e75fc31d65c9..2305563b40a6bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -2508,7 +2508,7 @@ internal void WriteLocalDecl(string variableName, SourceInfo initValue) Debug.Assert(initValue.MemberInfo.Name == initValue.Arg.Substring(3)); initValue.ILG.LoadMember(initValue.ILG.GetLocal("o"), initValue.MemberInfo); } - else if (initValue.Source.EndsWith("]", StringComparison.Ordinal)) + else if (initValue.Source.EndsWith(']')) { initValue.Load(initValue.Type); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs index 749386dc720f24..b74817ae5c0d25 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs @@ -12,7 +12,7 @@ internal static class NetCoreApiEmulators // On NetStandard, have to do with slower emulations. public static bool IsSignatureType(this Type type) => false; - public static bool IsSZArray(this Type type) => type.IsArray && type.GetArrayRank() == 1 && type.Name.EndsWith("[]"); + public static bool IsSZArray(this Type type) => type.IsArray && type.GetArrayRank() == 1 && type.Name.EndsWith("[]", StringComparison.Ordinal); public static bool IsVariableBoundArray(this Type type) => type.IsArray && !type.IsSZArray(); public static bool IsGenericMethodParameter(this Type type) => type.IsGenericParameter && type.DeclaringMethod != null; diff --git a/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs b/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs index 1b395834f0b97a..4c920ee4a1db96 100644 --- a/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs +++ b/src/libraries/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs @@ -270,7 +270,7 @@ private static bool LibpathMatchesPackagepath(string libpath, string packagepath StringComparison.OrdinalIgnoreCase) == 0 && // Ensure wzPackagePath is not just a prefix, but a path prefix // This says: packagepath is c:\foo || c:\foo\ - (libpath[packagepath.Length] == '\\' || packagepath.EndsWith("\\")); + (libpath[packagepath.Length] == '\\' || packagepath.EndsWith("\\", StringComparison.Ordinal)); } #if NETSTANDARD2_0 || NETCOREAPP diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonClassInfo.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonClassInfo.cs index e6fc4cc6cce7f8..d578645d3765ec 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonClassInfo.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonClassInfo.cs @@ -586,15 +586,15 @@ public static ClassType GetClassType( if (type.FullName != null) { - if (type.FullName.StartsWith("System.Collections.Generic.IEnumerable`1")) + if (type.FullName.StartsWith("System.Collections.Generic.IEnumerable`1", StringComparison.Ordinal)) { elementType = type.GetGenericArguments()[0]; runtimeType = typeof(List<>).MakeGenericType(elementType); addMethod = default; return ClassType.Enumerable; } - else if (type.FullName.StartsWith("System.Collections.Generic.IDictionary`2") || - type.FullName.StartsWith("System.Collections.Generic.IReadOnlyDictionary`2")) + else if (type.FullName.StartsWith("System.Collections.Generic.IDictionary`2", StringComparison.Ordinal) || + type.FullName.StartsWith("System.Collections.Generic.IReadOnlyDictionary`2", StringComparison.Ordinal)) { Type[] genericTypes = type.GetGenericArguments(); From 49d3bceac76b77a4f577db8cb199bfaf445a382b Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Fri, 7 Feb 2020 17:39:08 -0800 Subject: [PATCH 5/9] Avoid calling CultureInfo.InvariantCulture where possible --- .../src/Microsoft/VisualBasic/FileSystem.vb | 4 ++-- .../src/System/MemoryExtensions.Globalization.cs | 4 ++-- .../System.Private.CoreLib/src/System/String.Comparison.cs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb index a1427b5d616f1e..ff5b4c3253a5c3 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft/VisualBasic/FileSystem.vb @@ -75,7 +75,7 @@ Namespace Microsoft.VisualBasic End Sub Public Sub ChDrive(ByVal Drive As Char) - Drive = System.Char.ToUpper(Drive, CultureInfo.InvariantCulture) + Drive = System.Char.ToUpperInvariant(Drive) If (Drive < chLetterA) OrElse (Drive > chLetterZ) Then Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Drive")) @@ -110,7 +110,7 @@ Namespace Microsoft.VisualBasic Debug.Assert(Not System.Reflection.Assembly.GetCallingAssembly() Is Utils.VBRuntimeAssembly, "Methods in Microsoft.VisualBasic should not call FileSystem public method.") - Drive = System.Char.ToUpper(Drive, CultureInfo.InvariantCulture) + Drive = System.Char.ToUpperInvariant(Drive) If (Drive < chLetterA OrElse Drive > chLetterZ) Then Throw VbMakeException(New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Drive")), vbErrors.DevUnavailable) End If diff --git a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Globalization.cs b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Globalization.cs index 5bcdf8295ce4d3..604035e5e60523 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Globalization.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Globalization.cs @@ -269,7 +269,7 @@ public static int ToLowerInvariant(this ReadOnlySpan source, Span de if (GlobalizationMode.Invariant) TextInfo.ToLowerAsciiInvariant(source, destination); else - CultureInfo.InvariantCulture.TextInfo.ChangeCaseToLower(source, destination); + TextInfo.Invariant.ChangeCaseToLower(source, destination); return source.Length; } @@ -321,7 +321,7 @@ public static int ToUpperInvariant(this ReadOnlySpan source, Span de if (GlobalizationMode.Invariant) TextInfo.ToUpperAsciiInvariant(source, destination); else - CultureInfo.InvariantCulture.TextInfo.ChangeCaseToUpper(source, destination); + TextInfo.Invariant.ChangeCaseToUpper(source, destination); return source.Length; } diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs index 1baccf733f91bf..b664044be214c0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs @@ -763,7 +763,7 @@ public static int GetHashCode(ReadOnlySpan value, StringComparison compari case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: - return CultureInfo.InvariantCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType)); + return CompareInfo.Invariant.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return GetHashCode(value); From 33ca9f030ee5c1bb750ed186a9619a2a9f1e3534 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Fri, 7 Feb 2020 18:09:51 -0800 Subject: [PATCH 6/9] Use ordinal IndexOf(string) where necessary - Also uses IndexOf(char) if available --- .../Common/src/Interop/Linux/cgroups/Interop.cgroups.cs | 2 +- .../src/System/Net/NetworkInformation/UnixCommandLinePing.cs | 2 +- .../src/System/Composition/Hosting/Util/Formatters.cs | 2 +- .../src/System/Composition/Runtime/Util/Formatters.cs | 2 +- .../src/System/Configuration/ClientConfigPaths.cs | 4 ++-- .../src/System/Diagnostics/Process.Linux.cs | 2 +- .../src/System/Diagnostics/DelimitedListTraceListener.cs | 2 +- .../src/System/DirectoryServices/AccountManagement/Context.cs | 2 +- .../src/System/Drawing/Printing/PrintingServices.Unix.cs | 2 +- .../src/System/IO/Packaging/ContentType.cs | 2 +- .../src/System/Net/HttpListenerRequest.cs | 2 +- .../System.Private.CoreLib/src/System/Environment.Unix.cs | 2 +- .../System.Private.Xml/src/System/Xml/Serialization/Types.cs | 2 +- .../src/System/Security/Cryptography/Xml/Utils.cs | 4 ++-- 14 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/libraries/Common/src/Interop/Linux/cgroups/Interop.cgroups.cs b/src/libraries/Common/src/Interop/Linux/cgroups/Interop.cgroups.cs index e54b984d347aa5..287fc21ebedf0b 100644 --- a/src/libraries/Common/src/Interop/Linux/cgroups/Interop.cgroups.cs +++ b/src/libraries/Common/src/Interop/Linux/cgroups/Interop.cgroups.cs @@ -173,7 +173,7 @@ internal static bool TryFindHierarchyMount(string mountInfoFilePath, string subs // the end of the optional values. const string Separator = " - "; - int endOfOptionalFields = line.IndexOf(Separator); + int endOfOptionalFields = line.IndexOf(Separator, StringComparison.Ordinal); if (endOfOptionalFields == -1) { // Malformed line. diff --git a/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs b/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs index 3a5c413679f8ef..6747592aee02f6 100644 --- a/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs +++ b/src/libraries/Common/src/System/Net/NetworkInformation/UnixCommandLinePing.cs @@ -150,7 +150,7 @@ public static long ParseRoundTripTime(string pingOutput) { int timeIndex = pingOutput.IndexOf("time=", StringComparison.Ordinal); int afterTime = timeIndex + "time=".Length; - int msIndex = pingOutput.IndexOf("ms", afterTime); + int msIndex = pingOutput.IndexOf("ms", afterTime, StringComparison.Ordinal); int numLength = msIndex - afterTime - 1; string timeSubstring = pingOutput.Substring(afterTime, numLength); double parsedRtt = double.Parse(timeSubstring, CultureInfo.InvariantCulture); diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs index ad934f65fd27c6..8edc9727cdf0b8 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Util/Formatters.cs @@ -46,7 +46,7 @@ private static string FormatClosedGeneric(Type closedGenericType) throw new Exception(SR.Diagnostic_InternalExceptionMessage); } - var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf("`")); + var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`')); var args = closedGenericType.GenericTypeArguments.Select(t => Format(t)); return string.Format("{0}<{1}>", name, string.Join(", ", args)); } diff --git a/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs b/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs index 292a30dd2b074d..1c403dddd77eea 100644 --- a/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs +++ b/src/libraries/System.Composition.Runtime/src/System/Composition/Runtime/Util/Formatters.cs @@ -35,7 +35,7 @@ private static string FormatClosedGeneric(Type closedGenericType) { Debug.Assert(closedGenericType != null); Debug.Assert(closedGenericType.IsConstructedGenericType); - var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf("`")); + var name = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`')); IEnumerable args = closedGenericType.GenericTypeArguments.Select(t => Format(t)); return string.Format("{0}<{1}>", name, string.Join(SR.Formatter_ListSeparatorWithSpace, args)); } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs index 4a3070bd9259d7..1d37a0de5e03c8 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs @@ -272,7 +272,7 @@ private void SetNamesAndVersion(string applicationFilename, Assembly exeAssembly // Try the remainder of the namespace if (ns != null) { - int lastDot = ns.LastIndexOf(".", StringComparison.Ordinal); + int lastDot = ns.LastIndexOf('.'); if ((lastDot != -1) && (lastDot < ns.Length - 1)) ProductName = ns.Substring(lastDot + 1); else ProductName = ns; @@ -291,7 +291,7 @@ private void SetNamesAndVersion(string applicationFilename, Assembly exeAssembly // Try the first part of the namespace if (ns != null) { - int firstDot = ns.IndexOf(".", StringComparison.Ordinal); + int firstDot = ns.IndexOf('.'); _companyName = firstDot != -1 ? ns.Substring(0, firstDot) : ns; _companyName = _companyName.Trim(); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs index c2c0bd7267e026..1084f16c95631e 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs @@ -83,7 +83,7 @@ private static DateTime BootTime // It includes suspended time and is updated based on the system time (settimeofday). const string StatFile = Interop.procfs.ProcStatFilePath; string text = File.ReadAllText(StatFile); - int btimeLineStart = text.IndexOf("\nbtime "); + int btimeLineStart = text.IndexOf("\nbtime ", StringComparison.Ordinal); if (btimeLineStart >= 0) { int btimeStart = btimeLineStart + "\nbtime ".Length; diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs index f62a962c04be5a..898f767c4238f6 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs @@ -243,7 +243,7 @@ private void EscapeMessage(string message, StringBuilder sb) { int index; int lastindex = 0; - while ((index = message.IndexOf('"', lastindex)) != -1) + while ((index = message.IndexOf('\"', lastindex)) != -1) { sb.Append(message, lastindex, index - lastindex); sb.Append("\"\""); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs index b0094561b1c89e..0a63cb11da418b 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Context.cs @@ -104,7 +104,7 @@ private bool BindSam(string target, string userName, string password) // if they just passed user then append the machine name here. if (null != userName) { - int index = userName.IndexOf("\\", StringComparison.Ordinal); + int index = userName.IndexOf('\\'); if (index == -1) { userName = _serverName + "\\" + userName; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs index 21ee9ab7696cf4..98d87f549b92c8 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs @@ -411,7 +411,7 @@ private static PrinterResolution ParseResolution(string resolution) if (string.IsNullOrEmpty(resolution)) return null; - int dpiIndex = resolution.IndexOf("dpi"); + int dpiIndex = resolution.IndexOf("dpi", StringComparison.Ordinal); if (dpiIndex == -1) { // Resolution is "Unknown" or unparsable diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs index 05f4c385c0dc68..cb8e032453aaf1 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs @@ -403,7 +403,7 @@ private static int GetLengthOfParameterValue(string s, int startIndex) while (!found) { - length = s.IndexOf('"', ++length); + length = s.IndexOf('\"', ++length); if (length == -1) throw new ArgumentException(SR.InvalidParameterValue); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index d1b72728c21303..a6c4ecb4d93bae 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -343,7 +343,7 @@ internal static string GetCharSetValueFromHeader(string headerValue) { if (i == l - 1) return null; - j = headerValue.IndexOf('"', i + 1); + j = headerValue.IndexOf('\"', i + 1); if (j < 0 || j == i + 1) return null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs index 0d227417071a08..0e7c938ef37e66 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs @@ -255,7 +255,7 @@ private static string ReadXdgDirectory(string homeDir, string key, string fallba } // Find end of path - int endPos = line.IndexOf('"', pos); + int endPos = line.IndexOf('\"', pos); if (endPos <= pos) continue; // Got we need. Now extract it. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index 2f023ce9ebc2df..e19ae7a18f53b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -989,7 +989,7 @@ internal static string TypeName(Type t) StringBuilder typeName = new StringBuilder(); StringBuilder ns = new StringBuilder(); string name = t.Name; - int arity = name.IndexOf("`", StringComparison.Ordinal); + int arity = name.IndexOf('`'); if (arity >= 0) { name = name.Substring(0, arity); diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs index 7067873b925b2d..b758b1fbd13a0b 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/Utils.cs @@ -329,7 +329,7 @@ internal static string GetIdFromLocalUri(string uri, out bool discardComments) if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) { int startId = idref.IndexOf("id(", StringComparison.Ordinal); - int endId = idref.IndexOf(")", StringComparison.Ordinal); + int endId = idref.IndexOf(')'); if (endId < 0 || endId < startId + 3) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); idref = idref.Substring(startId + 3, endId - startId - 3); @@ -348,7 +348,7 @@ internal static string ExtractIdFromLocalUri(string uri) if (idref.StartsWith("xpointer(id(", StringComparison.Ordinal)) { int startId = idref.IndexOf("id(", StringComparison.Ordinal); - int endId = idref.IndexOf(")", StringComparison.Ordinal); + int endId = idref.IndexOf(')'); if (endId < 0 || endId < startId + 3) throw new CryptographicException(SR.Cryptography_Xml_InvalidReference); idref = idref.Substring(startId + 3, endId - startId - 3); From 2dd0022caf5ad6896e19822fb746730ad4668025 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Mon, 10 Feb 2020 16:21:02 -0800 Subject: [PATCH 7/9] PR feedback --- .../src/System/Diagnostics/DelimitedListTraceListener.cs | 2 +- .../System.IO.Packaging/src/System/IO/Packaging/ContentType.cs | 2 +- .../src/System/Net/HttpListenerRequest.cs | 2 +- .../System.Private.CoreLib/src/System/Environment.Unix.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs index 898f767c4238f6..f62a962c04be5a 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs @@ -243,7 +243,7 @@ private void EscapeMessage(string message, StringBuilder sb) { int index; int lastindex = 0; - while ((index = message.IndexOf('\"', lastindex)) != -1) + while ((index = message.IndexOf('"', lastindex)) != -1) { sb.Append(message, lastindex, index - lastindex); sb.Append("\"\""); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs index cb8e032453aaf1..05f4c385c0dc68 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs @@ -403,7 +403,7 @@ private static int GetLengthOfParameterValue(string s, int startIndex) while (!found) { - length = s.IndexOf('\"', ++length); + length = s.IndexOf('"', ++length); if (length == -1) throw new ArgumentException(SR.InvalidParameterValue); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index a6c4ecb4d93bae..d1b72728c21303 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -343,7 +343,7 @@ internal static string GetCharSetValueFromHeader(string headerValue) { if (i == l - 1) return null; - j = headerValue.IndexOf('\"', i + 1); + j = headerValue.IndexOf('"', i + 1); if (j < 0 || j == i + 1) return null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs index 0e7c938ef37e66..0d227417071a08 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Unix.cs @@ -255,7 +255,7 @@ private static string ReadXdgDirectory(string homeDir, string key, string fallba } // Find end of path - int endPos = line.IndexOf('\"', pos); + int endPos = line.IndexOf('"', pos); if (endPos <= pos) continue; // Got we need. Now extract it. From 6495888f7c43b640640fec2ba1e8b45e19a0d4a7 Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Tue, 11 Feb 2020 17:06:45 -0800 Subject: [PATCH 8/9] Make TextInfo.Invariant readonly --- .../src/System/Globalization/TextInfo.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 ea5a3d68e6a4ed..f8e2e0c4513450 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/TextInfo.cs @@ -45,7 +45,7 @@ private enum Tristate : byte private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized; // Invariant text info - internal static readonly TextInfo Invariant = new TextInfo(CultureData.Invariant); + internal static readonly TextInfo Invariant = new TextInfo(CultureData.Invariant, readOnly: true); internal TextInfo(CultureData cultureData) { @@ -57,6 +57,12 @@ internal TextInfo(CultureData cultureData) FinishInitialization(); } + private TextInfo(CultureData cultureData, bool readOnly) + : this(cultureData) + { + SetReadOnlyState(readOnly); + } + void IDeserializationCallback.OnDeserialization(object? sender) { throw new PlatformNotSupportedException(); From f3e0b7c241d414fd977f28f66759c8d4c2d6a1bd Mon Sep 17 00:00:00 2001 From: Levi Broderick Date: Tue, 11 Feb 2020 17:14:17 -0800 Subject: [PATCH 9/9] Fix some StartsWith call sites in System.Text.Json --- .../src/System/Text/Json/Serialization/ExtensionMethods.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ExtensionMethods.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ExtensionMethods.cs index 703ba02be213de..67acf6a887e4d0 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ExtensionMethods.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/ExtensionMethods.cs @@ -99,7 +99,7 @@ internal static class ExtensionMethods public static bool IsImmutableDictionaryType(this Type type) { - if (!type.IsGenericType || !type.Assembly.FullName!.StartsWith("System.Collections.Immutable,")) + if (!type.IsGenericType || !type.Assembly.FullName!.StartsWith("System.Collections.Immutable,", StringComparison.Ordinal)) { return false; } @@ -117,7 +117,7 @@ public static bool IsImmutableDictionaryType(this Type type) public static bool IsImmutableEnumerableType(this Type type) { - if (!type.IsGenericType|| !type.Assembly.FullName!.StartsWith("System.Collections.Immutable,")) + if (!type.IsGenericType|| !type.Assembly.FullName!.StartsWith("System.Collections.Immutable,", StringComparison.Ordinal)) { return false; }