From c0bb81807a3f4aeecfc63da31a32cc963ff0532c Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Tue, 9 May 2023 18:15:38 -0400 Subject: [PATCH] Use string.IsNullOrEmpty and ArgumentException.ThrowIfNullOrEmpty in many more places (#85858) --- .../ComponentModel/MaskedTextProvider.cs | 2 +- .../ComponentModel/PropertyDescriptor.cs | 2 +- .../System/ComponentModel/TypeDescriptor.cs | 2 +- .../src/System/Data/Common/ObjectStorage.cs | 2 +- .../src/System/Data/DataError.cs | 2 +- .../src/System/Data/DataSet.cs | 2 +- .../src/System/Data/SimpleType.cs | 2 +- .../src/System/Data/XDRSchema.cs | 14 +++---- .../src/System/Data/XMLSchema.cs | 38 +++++++++---------- .../src/System/Data/xmlsaver.cs | 14 +++---- .../src/System/Diagnostics/EventLog.cs | 10 ++--- .../Diagnostics/Reader/ProviderMetadata.cs | 2 +- .../System/Diagnostics/PerformanceCounter.cs | 4 +- .../Diagnostics/PerformanceCounterCategory.cs | 4 +- .../Diagnostics/SharedPerformanceCounter.cs | 4 +- .../AccountManagement/AD/ADStoreKey.cs | 2 +- .../AccountManagement/SAM/SAMUtils.cs | 2 +- .../Protocols/ldap/LdapConnection.cs | 2 +- .../DirectoryServices/DirectoryEntry.cs | 2 +- .../DirectoryServices/DirectorySearcher.cs | 2 +- .../PropertyValueCollection.cs | 2 +- .../tests/CultureInfo/CultureInfoAll.cs | 2 +- .../src/Resources/Strings.resx | 3 -- .../src/System/IO/Compression/ZipArchive.cs | 5 +-- .../IO/Pipes/NamedPipeServerStream.Unix.cs | 2 +- .../IO/Pipes/NamedPipeServerStream.Windows.cs | 2 +- .../src/System/Management/WMIGenerator.cs | 6 +-- .../src/System/Net/HttpListenerResponse.cs | 2 +- .../Managed/HttpListenerRequest.Managed.cs | 4 +- .../src/System/Net/Mail/Attachment.cs | 2 +- .../src/System/Net/Mail/SmtpClient.cs | 2 +- .../src/System/Net/Mime/ContentType.cs | 6 +-- .../src/System/Net/CookieContainer.cs | 2 +- .../src/Resources/Strings.resx | 6 --- .../src/System/Net/FileWebRequest.cs | 5 +-- .../src/System/Net/FtpWebRequest.cs | 13 ++----- .../src/System/Net/HttpWebRequest.cs | 5 +-- .../tests/FileWebRequestTest.cs | 2 +- .../tests/HttpWebRequestTest.cs | 2 +- .../src/System/DateOnly.cs | 2 +- .../System/Reflection/Emit/TypeNameBuilder.cs | 2 +- .../Runtime/Loader/AssemblyLoadContext.cs | 5 +-- .../src/System/TimeOnly.cs | 2 +- .../Serialization/ClassDataContract.cs | 2 +- .../Serialization/CollectionDataContract.cs | 6 +-- .../Runtime/Serialization/DataContract.cs | 4 +- .../Runtime/Serialization/EnumDataContract.cs | 2 +- .../Serialization/Json/JsonReaderDelegator.cs | 4 +- .../Runtime/Serialization/SchemaExporter.cs | 8 ++-- .../Runtime/Serialization/SchemaHelper.cs | 4 +- .../Serialization/XPathQueryGenerator.cs | 2 +- .../Runtime/Serialization/XmlDataContract.cs | 4 +- .../XmlObjectSerializerReadContext.cs | 2 +- .../Serialization/XmlReaderDelegator.cs | 6 +-- .../src/System/Xml/XmlBinaryWriter.cs | 2 +- .../tests/SDMSample/SDMXName.cs | 2 +- .../tests/misc/RegressionTests.cs | 2 +- .../tests/misc/XNameAPI.cs | 6 +-- .../Xml/Core/HtmlEncodedRawTextWriter.cs | 10 ++--- .../Core/HtmlRawTextWriterGenerator.ttinclude | 10 ++--- .../System/Xml/Core/HtmlUtf8RawTextWriter.cs | 10 ++--- .../System/Xml/Core/XmlCharCheckingWriter.cs | 15 ++------ .../Xml/Core/XmlCharCheckingWriterAsync.cs | 15 ++------ .../Xml/Core/XmlEncodedRawTextWriter.cs | 8 ++-- .../Xml/Core/XmlEncodedRawTextWriterAsync.cs | 8 ++-- .../Core/XmlRawTextWriterGenerator.ttinclude | 8 ++-- .../XmlRawTextWriterGeneratorAsync.ttinclude | 8 ++-- .../src/System/Xml/Core/XmlTextReaderImpl.cs | 4 +- .../src/System/Xml/Core/XmlTextWriter.cs | 31 ++++++--------- .../System/Xml/Core/XmlUtf8RawTextWriter.cs | 8 ++-- .../Xml/Core/XmlUtf8RawTextWriterAsync.cs | 8 ++-- .../Xml/Core/XmlValidatingReaderImpl.cs | 2 +- .../Xml/Core/XmlValidatingReaderImplAsync.cs | 2 +- .../System/Xml/Core/XmlWellFormedWriter.cs | 31 ++++----------- .../Xml/Core/XmlWellFormedWriterAsync.cs | 32 ++++------------ .../src/System/Xml/Core/XmlWriter.cs | 5 +-- .../src/System/Xml/Core/XmlWriterAsync.cs | 5 +-- .../System/Xml/Core/XsdValidatingReader.cs | 2 +- .../src/System/Xml/Dom/XmlNodeReader.cs | 6 +-- .../Xml/Dom/XmlProcessingInstruction.cs | 7 +--- .../Xml/Schema/DataTypeImplementation.cs | 12 +++--- .../src/System/Xml/Schema/FacetChecker.cs | 2 +- .../src/System/Xml/Schema/Preprocessor.cs | 6 +-- .../Schema/SchemaCollectionpreProcessor.cs | 2 +- .../src/System/Xml/Schema/XmlSchema.cs | 2 +- .../src/System/Xml/Schema/XmlSchemaAny.cs | 2 +- .../System/Xml/Schema/XmlSchemaCollection.cs | 2 +- .../src/System/Xml/Schema/XmlSchemaSet.cs | 2 +- .../System/Xml/Schema/XmlSchemaValidator.cs | 2 +- .../Xml/Serialization/CodeIdentifier.cs | 4 +- .../src/System/Xml/Serialization/Mappings.cs | 8 ++-- .../ReflectionXmlSerializationReader.cs | 2 +- .../ReflectionXmlSerializationWriter.cs | 3 +- .../Xml/Serialization/SchemaObjectWriter.cs | 10 ++--- .../Serialization/SoapReflectionImporter.cs | 4 +- .../System/Xml/Serialization/XmlAttributes.cs | 2 +- .../Serialization/XmlReflectionImporter.cs | 4 +- .../Xml/Serialization/XmlSchemaExporter.cs | 4 +- .../Xml/Serialization/XmlSchemaImporter.cs | 24 ++++++------ .../System/Xml/Serialization/XmlSchemas.cs | 8 ++-- .../Serialization/XmlSerializationReader.cs | 10 ++--- .../XmlSerializationReaderILGen.cs | 6 +-- .../Serialization/XmlSerializationWriter.cs | 28 +++++++------- .../XmlSerializationWriterILGen.cs | 4 +- .../src/System/Xml/XmlConvert.cs | 18 ++------- .../src/System/Xml/XmlQualifiedName.cs | 2 +- .../src/System/Xml/XmlResolver.cs | 2 +- .../src/System/Xml/Xsl/IlGen/XmlILModule.cs | 2 +- .../src/System/Xml/Xsl/QIL/QilXmlWriter.cs | 4 +- .../Xml/Xsl/Runtime/XmlAttributeCache.cs | 2 +- .../System/Xml/Xsl/Runtime/XmlQueryOutput.cs | 4 +- .../Xml/Xsl/XPath/XPathCompileException.cs | 2 +- .../src/System/Xml/Xsl/Xslt/XsltLoader.cs | 4 +- .../src/System/Xml/Xsl/XsltOld/BuilderInfo.cs | 2 +- .../src/System/Xml/Xsl/XsltOld/Compiler.cs | 2 +- .../Xml/Xsl/XsltOld/InputScopeManager.cs | 2 +- .../System/Xml/Xsl/XsltOld/NumberAction.cs | 2 +- .../Xml/Xsl/XsltOld/OutputScopeManager.cs | 4 +- .../Writers/RwFactory/CXmlDriverEngine.cs | 2 +- .../tests/XmlConvert/VerifyNameTests3.cs | 4 +- .../XmlSchemaValidatorApi/ValidateMisc.cs | 3 +- .../XsltArgumentList.cs | 4 +- .../Xslt/XslTransformApi/CXslTArgumentList.cs | 4 +- .../src/Resources/Strings.resx | 5 +-- .../Reflection/Emit/AssemblyBuilderImpl.cs | 5 +-- .../Emit/PseudoCustomAttributesData.cs | 2 +- .../Assemblies/Ecma/EcmaAssembly.Modules.cs | 2 +- .../Serialization/Schema/CodeExporter.cs | 2 +- .../CanonicalEncoder.cs | 2 +- .../CryptoCanonicalization/CanonicalWriter.cs | 4 +- .../SerializationTestTypes/DataContract.cs | 2 +- .../Security/Cryptography/Xml/SignedXml.cs | 2 +- .../System/Security/Cryptography/Xml/Utils.cs | 4 +- .../Xml/XmlDecryptionTransform.cs | 2 +- .../src/Resources/Strings.resx | 6 --- .../Security/Cryptography/CryptoConfig.cs | 10 +---- .../X500DistinguishedNameBuilder.cs | 4 +- ...X509AuthorityInformationAccessExtension.cs | 8 +--- .../X509Certificates/X509Extension.cs | 11 +----- .../X509Certificates/X509Pal.Android.cs | 2 +- .../X509Certificates/X509Pal.iOS.cs | 2 +- .../X509Certificates/X509Pal.macOS.cs | 2 +- .../tests/CryptoConfigTests.cs | 4 +- .../AuthorityInformationAccessTests.cs | 4 +- .../System/Security/Principal/NTAccount.cs | 2 +- .../Security/Principal/WindowsPrincipal.cs | 2 +- .../ServiceProcess/ServiceController.cs | 10 ++++- .../tests/SafeServiceControllerTests.cs | 9 ++--- .../src/Result/RecognizedWordUnit.cs | 2 +- .../System/Transactions/TransactionManager.cs | 2 +- 150 files changed, 344 insertions(+), 479 deletions(-) diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs index 5ca0b38163271..3bf597d297aa6 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs @@ -2710,7 +2710,7 @@ public bool VerifyString(string input, out int testPosition, out MaskedTextResul { testPosition = 0; - if (input == null || input.Length == 0) // nothing to verify. + if (string.IsNullOrEmpty(input)) // nothing to verify. { resultHint = MaskedTextResultHint.NoEffect; return true; diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs index aab9b3f496c98..51fad8dd06d90 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/PropertyDescriptor.cs @@ -336,7 +336,7 @@ public virtual PropertyDescriptorCollection GetChildProperties(object? instance, protected Type? GetTypeFromName( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] string? typeName) { - if (typeName == null || typeName.Length == 0) + if (string.IsNullOrEmpty(typeName)) { return null; } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs index c1f0cf44e0f44..b08f16cd9ae34 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -1136,7 +1136,7 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[]? name = component.Site.Name; } - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) { int ci = System.Threading.Interlocked.Increment(ref s_collisionIndex) - 1; name = ci.ToString(CultureInfo.InvariantCulture); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs index 3e8d0b3aa9dcc..c6f399c89fda9 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs @@ -359,7 +359,7 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute? { // this means type implements IXmlSerializable Type? type = null; string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); - if (typeName == null || typeName.Length == 0) + if (string.IsNullOrEmpty(typeName)) { // No CDT polumorphism string? xsdTypeName = xmlReader.GetAttribute(Keywords.TYPE, Keywords.XSINS); // this xsd type: Base type polymorphism if (null != xsdTypeName && xsdTypeName.Length > 0) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataError.cs b/src/libraries/System.Data.Common/src/System/Data/DataError.cs index 2657da25a7fc1..b098bebfdd3c7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataError.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataError.cs @@ -39,7 +39,7 @@ internal void SetColumnError(DataColumn column, string? error) { Debug.Assert(column != null, "Invalid (null) argument"); Debug.Assert(column.Table != null, "Invalid (loose) column"); - if (error == null || error.Length == 0) + if (string.IsNullOrEmpty(error)) { // remove error from the collection Clear(column); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index 50759ea83a961..a925c87c79218 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -748,7 +748,7 @@ public string DataSetName DataCommonEventSource.Log.Trace(" {0}, '{1}'", ObjectID, value); if (value != _dataSetName) { - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { throw ExceptionBuilder.SetDataSetNameToEmpty(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs index 9cd1233ff6deb..dafe0af9a9876 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs @@ -229,7 +229,7 @@ internal XmlNode ToNode(XmlDocument dc, Hashtable prefixes, bool inRemoting) { XmlElement typeNode = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SIMPLETYPE, Keywords.XSDNS); - if (_name != null && _name.Length != 0) + if (!string.IsNullOrEmpty(_name)) { // this is a global type typeNode.SetAttribute(Keywords.NAME, _name); diff --git a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs index 8b976e69a889e..33648f8d5ecbf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -41,7 +41,7 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) // Get Locale and CaseSensitive properties - if (_schemaName == null || _schemaName.Length == 0) + if (string.IsNullOrEmpty(_schemaName)) _schemaName = "NewDataSet"; ds.Namespace = _schemaUri; @@ -85,7 +85,7 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) if (FEqualIdentity(node, Keywords.XDR_ELEMENT, Keywords.XDRNS) || FEqualIdentity(node, Keywords.XDR_ATTRIBUTE, Keywords.XDRNS)) { - if (strType == null || strType.Length == 0) + if (string.IsNullOrEmpty(strType)) return null; // Find an ELEMENTTYPE or ATTRIBUTETYPE with name=strType @@ -133,7 +133,7 @@ internal static bool IsTextOnlyContent(XmlElement node) Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS), $"Invalid node type {node.LocalName}"); string value = node.GetAttribute(Keywords.CONTENT); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { string type = node.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); return !string.IsNullOrEmpty(type); @@ -311,7 +311,7 @@ private static Type ParseDataType(string dt, string dtValues) } NameType nt = FindNameType(strType); - if (nt == s_enumerationNameType && (dtValues == null || dtValues.Length == 0)) + if (nt == s_enumerationNameType && string.IsNullOrEmpty(dtValues)) throw ExceptionBuilder.MissingAttribute("type", Keywords.DT_VALUES); return nt.type; } @@ -332,7 +332,7 @@ internal static string GetInstanceName(XmlElement node) else { instanceName = node.GetAttribute(Keywords.TYPE); - if (instanceName == null || instanceName.Length == 0) + if (string.IsNullOrEmpty(instanceName)) throw ExceptionBuilder.MissingAttribute("Element", Keywords.TYPE); } @@ -400,7 +400,7 @@ internal void HandleColumn(XmlElement node, DataTable table) strType = typeNode.GetAttribute(Keywords.DT_TYPE, Keywords.DTNS); strValues = typeNode.GetAttribute(Keywords.DT_VALUES, Keywords.DTNS); - if (strType == null || strType.Length == 0) + if (string.IsNullOrEmpty(strType)) { strType = string.Empty; type = typeof(string); @@ -480,7 +480,7 @@ internal void HandleColumn(XmlElement node, DataTable table) column.Namespace = targetNamespace; table.Columns.Add(column); - if (strDefault != null && strDefault.Length != 0) + if (!string.IsNullOrEmpty(strDefault)) try { column.DefaultValue = SqlConvert.ChangeTypeForXML(strDefault, type); 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 0faa0202d5609..8744eefaf8471 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -80,7 +80,7 @@ internal static bool FEqualIdentity(XmlNode? node, string name, string ns) internal static bool GetBooleanAttribute(XmlElement element, string attrName, string attrNS, bool defVal) { string value = element.GetAttribute(attrName, attrNS); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { return defVal; } @@ -447,22 +447,22 @@ internal void HandleRelation(XmlElement node, bool fNested) } parentName = node.GetAttribute(Keywords.MSD_PARENT, Keywords.MSDNS); - if (parentName == null || parentName.Length == 0) + if (string.IsNullOrEmpty(parentName)) throw ExceptionBuilder.RelationParentNameMissing(strName); parentName = XmlConvert.DecodeName(parentName); childName = node.GetAttribute(Keywords.MSD_CHILD, Keywords.MSDNS); - if (childName == null || childName.Length == 0) + if (string.IsNullOrEmpty(childName)) throw ExceptionBuilder.RelationChildNameMissing(strName); childName = XmlConvert.DecodeName(childName); value = node.GetAttribute(Keywords.MSD_PARENTKEY, Keywords.MSDNS); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) throw ExceptionBuilder.RelationTableKeyMissing(strName); parentNames = value.TrimEnd(null).Split(new char[] { Keywords.MSD_KEYFIELDSEP, Keywords.MSD_KEYFIELDOLDSEP }); value = node.GetAttribute(Keywords.MSD_CHILDKEY, Keywords.MSDNS); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) throw ExceptionBuilder.RelationChildKeyMissing(strName); childNames = value.TrimEnd(null).Split(new char[] { Keywords.MSD_KEYFIELDSEP, Keywords.MSD_KEYFIELDOLDSEP }); @@ -666,7 +666,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) { _schemaName = schemaRoot.Id; - if (_schemaName == null || _schemaName.Length == 0) + if (string.IsNullOrEmpty(_schemaName)) { _schemaName = "NewDataSet"; } @@ -1208,7 +1208,7 @@ internal static DataColumn[] BuildKey(XmlSchemaIdentityConstraint keyNode, DataT internal static bool GetBooleanAttribute(XmlSchemaAnnotated element, string attrName, bool defVal) { string? value = GetMsdataAttribute(element, attrName); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { return defVal; } @@ -1227,7 +1227,7 @@ internal static bool GetBooleanAttribute(XmlSchemaAnnotated element, string attr internal static string GetStringAttribute(XmlSchemaAnnotated element, string attrName, string defVal) { string? value = GetMsdataAttribute(element, attrName); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { return defVal; } @@ -1287,7 +1287,7 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) if (table == null) return; - if (refer == null || refer.Length == 0) + if (string.IsNullOrEmpty(refer)) throw ExceptionBuilder.MissingRefer(name); ConstraintTable? key = (ConstraintTable?)_constraintNodes![refer]; @@ -1321,7 +1321,7 @@ internal void HandleKeyref(XmlSchemaKeyref keyref) { string relName = XmlConvert.DecodeName(GetStringAttribute(keyref, Keywords.MSD_RELATIONNAME, keyref.Name!)); - if (relName == null || relName.Length == 0) + if (string.IsNullOrEmpty(relName)) relName = name; int iExisting = fKey[0].Table!.DataSet!.Relations.InternalIndexOf(relName); @@ -1383,7 +1383,7 @@ internal void HandleConstraint(XmlSchemaIdentityConstraint keyNode) string? name; name = XmlConvert.DecodeName(keyNode.Name); - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) throw ExceptionBuilder.MissingAttribute(Keywords.NAME); if (_constraintNodes!.ContainsKey(name)) @@ -1930,10 +1930,10 @@ internal static bool IsXsdType(string name) if (_typeNs == Keywords.XSDNS) return null; XmlSchemaAnnotated? typeNode; - if (_type == null || _type.Length == 0) + if (string.IsNullOrEmpty(_type)) { _type = isAttr ? attr!.RefName.Name : el!.RefName.Name; - if (_type == null || _type.Length == 0) + if (string.IsNullOrEmpty(_type)) typeNode = isAttr ? attr!.SchemaType : el!.SchemaType; else typeNode = isAttr ? FindTypeNode((XmlSchemaAnnotated)_attributes![attr!.RefName]!) : FindTypeNode((XmlSchemaAnnotated)_elementsTable![el!.RefName]!); @@ -1956,7 +1956,7 @@ internal void HandleSimpleTypeSimpleContentColumn(XmlSchemaSimpleType typeNode, SimpleType? xsdType = null; // if (typeNode.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType - if (typeNode.QualifiedName.Name != null && typeNode.QualifiedName.Name.Length != 0 && typeNode.QualifiedName.Namespace != Keywords.XSDNS) + if (!string.IsNullOrEmpty(typeNode.QualifiedName.Name) && typeNode.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType xsdType = new SimpleType(typeNode); strType = typeNode.QualifiedName.ToString(); // use qualified name @@ -2212,7 +2212,7 @@ internal void HandleAttributeColumn(XmlSchemaAttribute attrib, DataTable table, { XmlSchemaSimpleType node = (typeNode as XmlSchemaSimpleType)!; xsdType = new SimpleType(node); - if (node.QualifiedName.Name != null && node.QualifiedName.Name.Length != 0 && node.QualifiedName.Namespace != Keywords.XSDNS) + if (!string.IsNullOrEmpty(node.QualifiedName.Name) && node.QualifiedName.Namespace != Keywords.XSDNS) { // this means UDSimpleType strType = node.QualifiedName.ToString(); // use qualified name @@ -2376,7 +2376,7 @@ internal void HandleElementColumn(XmlSchemaElement elem, DataTable table, bool i xsdType = new SimpleType(simpleTypeNode!); // ((XmlSchemaSimpleType)typeNode).Name != null && ((XmlSchemaSimpleType)typeNode).Name.Length != 0 check is for annonymos simple type, // it should be user defined Named simple type - if (((XmlSchemaSimpleType)typeNode).Name != null && ((XmlSchemaSimpleType)typeNode).Name!.Length != 0 && ((XmlSchemaSimpleType)typeNode).QualifiedName.Namespace != Keywords.XSDNS) + if (!string.IsNullOrEmpty(((XmlSchemaSimpleType)typeNode).Name) && ((XmlSchemaSimpleType)typeNode).QualifiedName.Namespace != Keywords.XSDNS) { strType = ((XmlSchemaSimpleType)typeNode).QualifiedName.ToString(); // use qualified name type = ParseDataType(strType); @@ -2582,13 +2582,13 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) // reuse variable value = GetMsdataAttribute(node, Keywords.MSD_DATASETNAME); - if (value != null && value.Length != 0) + if (!string.IsNullOrEmpty(value)) { dsName = value; } value = GetMsdataAttribute(node, Keywords.MSD_DATASETNAMESPACE); - if (value != null && value.Length != 0) + if (!string.IsNullOrEmpty(value)) { dsNamespace = value; } @@ -2597,7 +2597,7 @@ internal void HandleDataSet(XmlSchemaElement node, bool isNewDataSet) SetExtProperties(_ds, node.UnhandledAttributes); - if (dsName != null && dsName.Length != 0) + if (!string.IsNullOrEmpty(dsName)) _ds.DataSetName = XmlConvert.DecodeName(dsName); // _ds.Namespace = node.QualifiedName.Namespace; diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index ee1b300f3f430..e7cf97ac6c2c2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -1250,7 +1250,7 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, XmlNode type; string? name = stNode.Name; - if (name != null && name.Length != 0) + if (!string.IsNullOrEmpty(name)) { // For remoting, always need to work with root schema's namespace string nSpace = (_schFormat != SchemaFormat.Remoting) ? stNode.Namespace : @@ -1314,7 +1314,7 @@ internal void HandleColumnType(DataColumn col, XmlDocument dc, XmlElement root, else { string typeName = XmlDataTypeName(col.DataType); // do not update the hashtable, as it will not write msdata:DataType - if (typeName == null || typeName.Length == 0) + if (string.IsNullOrEmpty(typeName)) { if (col.DataType == typeof(Guid) || col.DataType == typeof(Type)) { @@ -1812,7 +1812,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche // the type for this element DataColumn col = table.Columns[0]; string _typeName = XmlDataTypeName(col.DataType); - if (_typeName == null || _typeName.Length == 0) + if (string.IsNullOrEmpty(_typeName)) { _typeName = Keywords.XSD_ANYTYPE; } @@ -2445,7 +2445,7 @@ private void GenerateTableErrors(DataTable table) DataColumn column = table.Columns[colNum]; string error = row.GetColumnError(column); string columnPrefix = (column.Namespace.Length != 0) ? column.Prefix : string.Empty; - if (error == null || error.Length == 0) + if (string.IsNullOrEmpty(error)) { continue; } @@ -2770,7 +2770,7 @@ internal static bool RowHasErrors(DataRow row) { DataColumn column = row.Table.Columns[colNum]; string error = row.GetColumnError(column); - if (error == null || error.Length == 0) + if (string.IsNullOrEmpty(error)) { continue; } @@ -2794,7 +2794,7 @@ internal void SaveDiffgramData(XmlWriter xw, Hashtable rowsOrder) string prefix = (_ds != null) ? ((_ds.Namespace.Length == 0) ? "" : _ds.Prefix) : ((_dt!.Namespace.Length == 0) ? "" : _dt.Prefix); - if (_ds == null || _ds.DataSetName == null || _ds.DataSetName.Length == 0) + if (_ds == null || string.IsNullOrEmpty(_ds.DataSetName)) _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, (_dt!.Namespace == null) ? "" : _dt.Namespace); else _xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace); @@ -2852,7 +2852,7 @@ internal void Save(XmlWriter xw, bool writeSchema) } else { - if (_ds.DataSetName == null || _ds.DataSetName.Length == 0) + if (string.IsNullOrEmpty(_ds.DataSetName)) _xmlw.WriteStartElement(prefix, Keywords.DOCUMENTELEMENT, _ds.Namespace); else _xmlw.WriteStartElement(prefix, XmlConvert.EncodeLocalName(_ds.DataSetName), _ds.Namespace); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index ae43e819f34ae..762a7ce6fae65 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -256,11 +256,11 @@ public static void CreateEventSource(EventSourceCreationData sourceData) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } - if (logName == null || logName.Length == 0) + if (string.IsNullOrEmpty(logName)) logName = "Application"; if (!ValidLogName(logName, false)) throw new ArgumentException(SR.BadLogName); - if (source == null || source.Length == 0) + if (string.IsNullOrEmpty(source)) throw new ArgumentException(SR.Format(SR.MissingParameter, nameof(source))); if (source.Length + EventLogKey.Length > 254) throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length)); @@ -363,7 +363,7 @@ public static void Delete(string logName, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName)), nameof(machineName)); - if (logName == null || logName.Length == 0) + if (string.IsNullOrEmpty(logName)) throw new ArgumentException(SR.NoLogName); if (!ValidLogName(logName, false)) throw new InvalidOperationException(SR.BadLogName); @@ -501,7 +501,7 @@ public static bool Exists(string logName, string machineName) if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName))); - if (logName == null || logName.Length == 0) + if (string.IsNullOrEmpty(logName)) return false; RegistryKey eventkey = null; @@ -530,7 +530,7 @@ private static RegistryKey FindSourceRegistration(string source, string machineN private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly, bool wantToCreate) { - if (source != null && source.Length != 0) + if (!string.IsNullOrEmpty(source)) { RegistryKey eventkey = null; try diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs index 01e201c2bfe08..bebfaa094e5e7 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs @@ -118,7 +118,7 @@ public Uri HelpLink get { string helpLinkStr = (string)NativeWrapper.EvtGetPublisherMetadataProperty(_handle, UnsafeNativeMethods.EvtPublisherMetadataPropertyId.EvtPublisherMetadataHelpLink); - if (helpLinkStr == null || helpLinkStr.Length == 0) + if (string.IsNullOrEmpty(helpLinkStr)) return null; return new Uri(helpLinkStr); } 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 9f200fac46edb..dd4ec93705f30 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs @@ -548,14 +548,14 @@ public CounterSample NextSample() _counterType = counterSample._counterType; if (!categorySample._isMultiInstance) { - if (_instanceName != null && _instanceName.Length != 0) + if (!string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, _instanceName)); return counterSample.GetSingleValue(); } else { - if (_instanceName == null || _instanceName.Length == 0) + if (string.IsNullOrEmpty(_instanceName)) throw new InvalidOperationException(SR.InstanceNameRequired); return counterSample.GetInstanceValue(_instanceName); 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 9b4f2c62d3625..a31e60d0d9e71 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterCategory.cs @@ -306,7 +306,7 @@ internal static void CheckValidCounterLayout(CounterCreationDataCollection count Hashtable h = new Hashtable(); for (int i = 0; i < counterData.Count; i++) { - if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0) + if (string.IsNullOrEmpty(counterData[i].CounterName)) { throw new ArgumentException(SR.InvalidCounterName); } @@ -362,7 +362,7 @@ internal static void CheckValidCounterLayout(CounterCreationDataCollection count h.Add(counterData[i].CounterName, string.Empty); // Ensure that all counter help strings aren't null or empty - if (counterData[i].CounterHelp == null || counterData[i].CounterHelp.Length == 0) + if (string.IsNullOrEmpty(counterData[i].CounterHelp)) { counterData[i].CounterHelp = counterData[i].CounterName; } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs index 8ec76b9096007..69729ef5d6101 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/SharedPerformanceCounter.cs @@ -739,7 +739,7 @@ private static void RemoveCategoryData(string categoryName) { int counterNameHashCode = GetWstrHashCode(counterName); int instanceNameHashCode; - if (instanceName != null && instanceName.Length != 0) + if (!string.IsNullOrEmpty(instanceName)) instanceNameHashCode = GetWstrHashCode(instanceName); else { @@ -1423,7 +1423,7 @@ private unsafe void RemoveAllInstances() internal unsafe void RemoveInstance(string instanceName, PerformanceCounterInstanceLifetime instanceLifetime) { - if (instanceName == null || instanceName.Length == 0) + if (string.IsNullOrEmpty(instanceName)) return; int instanceNameHashCode = GetWstrHashCode(instanceName); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs index e3cd6693a7f41..5c47a7d3f8681 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreKey.cs @@ -33,7 +33,7 @@ public ADStoreKey(Guid guid) public ADStoreKey(string domainName, byte[] sid) { - Debug.Assert(domainName != null && domainName.Length > 0); + Debug.Assert(!string.IsNullOrEmpty(domainName)); Debug.Assert(sid != null && sid.Length != 0); // Make a copy of the SID, since a byte[] is mutable diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMUtils.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMUtils.cs index 9ea29c680ad6e..1ce1cafc5ed16 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMUtils.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMUtils.cs @@ -48,7 +48,7 @@ internal static bool GetOSVersion(DirectoryEntry computerDE, out int versionMajo } // Couldn't retrieve the value - if (version == null || version.Length == 0) + if (string.IsNullOrEmpty(version)) return false; // This string should be in the form "M.N", where M and N are integers. diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index 8184c2173d6ce..0d478c6167ca1 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -1063,7 +1063,7 @@ private void BindHelper(NetworkCredential newCredential, bool needSetCredential) else if (AuthType == AuthType.Basic) { var tempDomainName = new StringBuilder(100); - if (domainName != null && domainName.Length != 0) + if (!string.IsNullOrEmpty(domainName)) { tempDomainName.Append(domainName); tempDomainName.Append('\\'); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs index c4d046cf00656..54e26eb3653b4 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs @@ -510,7 +510,7 @@ internal void Bind(bool throwIfFail) if (_adsObject == null) { string pathToUse = Path; - if (pathToUse == null || pathToUse.Length == 0) + if (string.IsNullOrEmpty(pathToUse)) { // get the default naming context. This should be the default root for the search. DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", true, null, null, AuthenticationTypes.Secure); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs index 37f2018d70bc6..65d921448894b 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs @@ -200,7 +200,7 @@ public string? Filter get => _filter; set { - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) value = defaultFilter; _filter = value; } diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs index a006b65e7e4bb..6a23f61fb07bd 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs @@ -33,7 +33,7 @@ internal PropertyValueCollection(DirectoryEntry entry, string propertyName) _changeList = ArrayList.Synchronized(tempList); _allowMultipleChange = entry.allowMultipleChange; string tempPath = entry.Path; - if (tempPath == null || tempPath.Length == 0) + if (string.IsNullOrEmpty(tempPath)) { // user does not specify path, so we bind to default naming context using LDAP provider. _needNewBehavior = true; diff --git a/src/libraries/System.Globalization/tests/CultureInfo/CultureInfoAll.cs b/src/libraries/System.Globalization/tests/CultureInfo/CultureInfoAll.cs index fb9ca3f92e79e..fb4692da1a0ab 100644 --- a/src/libraries/System.Globalization/tests/CultureInfo/CultureInfoAll.cs +++ b/src/libraries/System.Globalization/tests/CultureInfo/CultureInfoAll.cs @@ -148,7 +148,7 @@ private void ValidateRegionInfo(CultureInfo ci) private int[] ConvertWin32GroupString(string win32Str) { // None of these cases make any sense - if (win32Str == null || win32Str.Length == 0) + if (string.IsNullOrEmpty(win32Str)) { return (new int[] { 3 }); } diff --git a/src/libraries/System.IO.Compression/src/Resources/Strings.resx b/src/libraries/System.IO.Compression/src/Resources/Strings.resx index 3f689162599d2..94fa155281d93 100644 --- a/src/libraries/System.IO.Compression/src/Resources/Strings.resx +++ b/src/libraries/System.IO.Compression/src/Resources/Strings.resx @@ -170,9 +170,6 @@ The underlying compression routine returned an unexpected error code. - - String cannot be empty. - Central Directory corrupt. diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs index 6d6b0e8662f27..a6133a62ba286 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/ZipArchive.cs @@ -391,10 +391,7 @@ private set private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compressionLevel) { - ArgumentNullException.ThrowIfNull(entryName); - - if (string.IsNullOrEmpty(entryName)) - throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName)); + ArgumentException.ThrowIfNullOrEmpty(entryName); if (_mode == ZipArchiveMode.Read) throw new NotSupportedException(SR.CreateInReadMode); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs index 8544186c1c049..00973263355fe 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs @@ -26,7 +26,7 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { - Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty"); + Debug.Assert(!string.IsNullOrEmpty(pipeName), "fullPipeName is null or empty"); Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction"); Debug.Assert(inBufferSize >= 0, "inBufferSize is negative"); Debug.Assert(outBufferSize >= 0, "outBufferSize is negative"); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs index 9c1e385a7c4f2..c0f066da80521 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs @@ -80,7 +80,7 @@ private void Create(string pipeName, PipeDirection direction, int maxNumberOfSer PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity? pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights) { - Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty"); + Debug.Assert(!string.IsNullOrEmpty(pipeName), "fullPipeName is null or empty"); Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction"); Debug.Assert(inBufferSize >= 0, "inBufferSize is negative"); Debug.Assert(outBufferSize >= 0, "outBufferSize is negative"); diff --git a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs index 396a2bc303f28..f60168c9cb976 100644 --- a/src/libraries/System.Management/src/System/Management/WMIGenerator.cs +++ b/src/libraries/System.Management/src/System/Management/WMIGenerator.cs @@ -957,7 +957,7 @@ private void GeneratePublicReadOnlyProperty(string propName, string propType, st cmp.GetStatements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(propValue))); } cc.Members.Add(cmp); - if (Comment != null && Comment.Length != 0) + if (!string.IsNullOrEmpty(Comment)) { cmp.Comments.Add(new CodeCommentStatement(Comment)); } @@ -1001,7 +1001,7 @@ private void GeneratePublicProperty(string propName, string propType, CodeExpres new CodeSnippetExpression("value"))); cc.Members.Add(cmp); - if (Comment != null && Comment.Length != 0) + if (!string.IsNullOrEmpty(Comment)) { cmp.Comments.Add(new CodeCommentStatement(Comment)); } @@ -3710,7 +3710,7 @@ private void GeneratePrivateMember(string memberName, string MemberType, CodeExp } cc.Members.Add(cf); - if (Comment != null && Comment.Length != 0) + if (!string.IsNullOrEmpty(Comment)) { cf.Comments.Add(new CodeCommentStatement(Comment)); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index 68992ba46dfdb..c9460816eceed 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -202,7 +202,7 @@ private void ComputeCookies() { Cookie cookie = _cookies[index]; string cookieString = cookie.ToServerString(); - if (cookieString == null || cookieString.Length == 0) + if (string.IsNullOrEmpty(cookieString)) { continue; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index a8bad6f71d62a..651a5f39ad39d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -163,7 +163,7 @@ private static bool IsPredefinedScheme(string scheme) internal void FinishInitialization() { string host = UserHostName; - if (_version > HttpVersion.Version10 && (host == null || host.Length == 0)) + if (_version > HttpVersion.Version10 && string.IsNullOrEmpty(host)) { _context.ErrorMessage = "Invalid host name"; return; @@ -177,7 +177,7 @@ internal void FinishInitialization() else path = _rawUrl; - if ((host == null || host.Length == 0)) + if (string.IsNullOrEmpty(host)) host = UserHostAddress; if (raw_uri != null) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs index 8c646058a8e38..93e472fc9b426 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs @@ -341,7 +341,7 @@ public Attachment(Stream contentStream, ContentType contentType) : internal void SetContentTypeName(bool allowUnicode) { - if (!allowUnicode && _name != null && _name.Length != 0 && !MimeBasePart.IsAscii(_name, false)) + if (!allowUnicode && !string.IsNullOrEmpty(_name) && !MimeBasePart.IsAscii(_name, false)) { Encoding encoding = NameEncoding ?? Encoding.GetEncoding(MimeBasePart.DefaultCharSet); MimePart.ContentType.Name = MimeBasePart.EncodeHeaderValue(_name, encoding, MimeBasePart.ShouldUseBase64Encoding(encoding)); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index eb97f48260cfb..26a496f87a635 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -811,7 +811,7 @@ internal bool InCall private void CheckHostAndPort() { - if (_host == null || _host.Length == 0) + if (string.IsNullOrEmpty(_host)) { throw new InvalidOperationException(SR.UnspecifiedHost); } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs index 2aa889e099fab..55d7b51b42d88 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs @@ -224,13 +224,13 @@ private void ParseValue() int offset = 0; _mediaType = MailBnfHelper.ReadToken(_type, ref offset); - if (_mediaType == null || _mediaType.Length == 0 || offset >= _type.Length || _type[offset++] != '/') + if (string.IsNullOrEmpty(_mediaType) || offset >= _type.Length || _type[offset++] != '/') { throw new FormatException(SR.ContentTypeInvalid); } _subType = MailBnfHelper.ReadToken(_type, ref offset); - if (_subType == null || _subType.Length == 0) + if (string.IsNullOrEmpty(_subType)) { throw new FormatException(SR.ContentTypeInvalid); } @@ -249,7 +249,7 @@ private void ParseValue() string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset); - if (paramAttribute == null || paramAttribute.Length == 0) + if (string.IsNullOrEmpty(paramAttribute)) { throw new FormatException(SR.ContentTypeInvalid); } 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 357a343c7896f..cd1d96b571c7d 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -817,7 +817,7 @@ public CookieCollection GetAllCookies() // DNS.resolve may return short names even for other inet domains ;-( // We _don't_ know what the exact domain is, so try also grab short hostname cookies. // Grab long name from the local domain - if (m_fqdnMyDomain != null && m_fqdnMyDomain.Length != 0) + if (!string.IsNullOrEmpty(m_fqdnMyDomain)) { domainAttributeMatchAnyCookieVariant.Add(fqdnRemote + m_fqdnMyDomain); // Grab the local domain itself diff --git a/src/libraries/System.Net.Requests/src/Resources/Strings.resx b/src/libraries/System.Net.Requests/src/Resources/Strings.resx index fd367c6ae20ea..f8ac54eb739cd 100644 --- a/src/libraries/System.Net.Requests/src/Resources/Strings.resx +++ b/src/libraries/System.Net.Requests/src/Resources/Strings.resx @@ -168,12 +168,6 @@ The data connection was made from an address that is different than the address to which the FTP connection was made. - - FTP Method names cannot be null or empty. - - - The RenameTo filename cannot be null or empty. - The server returned the filename ({0}) which is not valid. diff --git a/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs index 7a938664b5ceb..e643354699d35 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FileWebRequest.cs @@ -82,10 +82,7 @@ public override string Method get { return _method; } set { - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentException(SR.net_badmethod, nameof(value)); - } + ArgumentException.ThrowIfNullOrEmpty(value); _method = value; } } 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 873d49add936a..5a6009240fd92 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -261,10 +261,8 @@ public override string Method } set { - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentException(SR.net_ftp_invalid_method_name, nameof(value)); - } + ArgumentException.ThrowIfNullOrEmpty(value); + if (InUse) { throw new InvalidOperationException(SR.net_reqsubmitted); @@ -300,10 +298,7 @@ public string? RenameTo throw new InvalidOperationException(SR.net_reqsubmitted); } - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentException(SR.net_ftp_invalid_renameto, nameof(value)); - } + ArgumentException.ThrowIfNullOrEmpty(value); _renameTo = value; } @@ -497,7 +492,7 @@ internal FtpWebRequest(Uri uri) NetworkCredential? networkCredential = null; _uri = uri; _methodInfo = FtpMethodInfo.GetMethodInfo(WebRequestMethods.Ftp.DownloadFile); - if (_uri.UserInfo != null && _uri.UserInfo.Length != 0) + if (!string.IsNullOrEmpty(_uri.UserInfo)) { string userInfo = _uri.UserInfo; string username = userInfo; diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs index 5362745761ba1..f99a052ff0ace 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -905,10 +905,7 @@ public override string Method } set { - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentException(SR.net_badmethod, nameof(value)); - } + ArgumentException.ThrowIfNullOrEmpty(value); if (HttpValidationHelpers.IsInvalidMethodOrHeaderString(value)) { diff --git a/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs index e845bc35d5c4c..52aa464505fb0 100644 --- a/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/FileWebRequestTest.cs @@ -52,7 +52,7 @@ public void InvalidArguments_Throws() { WebRequest request = WebRequest.Create("file://anything"); AssertExtensions.Throws("value", () => request.ContentLength = -1); - AssertExtensions.Throws("value", () => request.Method = null); + AssertExtensions.Throws("value", () => request.Method = null); AssertExtensions.Throws("value", () => request.Method = ""); AssertExtensions.Throws("value", () => request.Timeout = -2); } diff --git a/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs b/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs index 835f88a5677e3..ebd3c53d1d573 100644 --- a/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs +++ b/src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs @@ -1555,7 +1555,7 @@ public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer) public void Method_SetInvalidString_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); - AssertExtensions.Throws("value", () => request.Method = null); + AssertExtensions.Throws("value", () => request.Method = null); AssertExtensions.Throws("value", () => request.Method = string.Empty); AssertExtensions.Throws("value", () => request.Method = "Method(2"); } diff --git a/src/libraries/System.Private.CoreLib/src/System/DateOnly.cs b/src/libraries/System.Private.CoreLib/src/System/DateOnly.cs index 9ee652e823ed5..44484797af971 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateOnly.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateOnly.cs @@ -739,7 +739,7 @@ private static void ThrowOnError(ParseFailureKind result, ReadOnlySpan s) /// A string representation of value of the current DateOnly object as specified by format and provider. public string ToString([StringSyntax(StringSyntaxAttribute.DateOnlyFormat)] string? format, IFormatProvider? provider) { - if (format == null || format.Length == 0) + if (string.IsNullOrEmpty(format)) { format = "d"; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeNameBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeNameBuilder.cs index 246d4e0581082..daccffbb96684 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeNameBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/TypeNameBuilder.cs @@ -316,7 +316,7 @@ private void AddAssemblyQualifiedName(Type type, Format format) Type enclosingType = nestings[i]; string name = enclosingType.Name; - if (i == nestings.Count - 1 && enclosingType.Namespace != null && enclosingType.Namespace.Length != 0) + if (i == nestings.Count - 1 && !string.IsNullOrEmpty(enclosingType.Namespace)) name = enclosingType.Namespace + "." + name; AddName(name); diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs index 2e8fcb7d4a0df..d7ba398a03f45 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.cs @@ -645,10 +645,7 @@ public void Dispose() private static Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string? requestedSimpleName) { - if (string.IsNullOrEmpty(requestedSimpleName)) - { - throw new ArgumentException(SR.ArgumentNull_AssemblyNameName); - } + ArgumentException.ThrowIfNullOrEmpty(requestedSimpleName, "AssemblyName.Name"); // Get the name of the loaded assembly string? loadedSimpleName = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeOnly.cs b/src/libraries/System.Private.CoreLib/src/System/TimeOnly.cs index a30ab1e87d0bb..65d80ce153450 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeOnly.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeOnly.cs @@ -914,7 +914,7 @@ private static void ThrowOnError(ParseFailureKind result, ReadOnlySpan s) /// The accepted standard formats are 'r', 'R', 'o', 'O', 't' and 'T'. public string ToString([StringSyntax(StringSyntaxAttribute.TimeOnlyFormat)] string? format, IFormatProvider? provider) { - if (format == null || format.Length == 0) + if (string.IsNullOrEmpty(format)) { format = "t"; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs index aae72d1f3e117..f3b28edf11123 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs @@ -853,7 +853,7 @@ private void ImportDataMembers() DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; if (memberAttribute.IsNameSetExplicitly) { - if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) + if (string.IsNullOrEmpty(memberAttribute.Name)) ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Name; } 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 a9b1042a26d11..8d20b6d7a2897 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 @@ -455,14 +455,14 @@ private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAtt { if (collectionContractAttribute.IsItemNameSetExplicitly) { - if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) + if (string.IsNullOrEmpty(collectionContractAttribute.ItemName)) throw new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))); itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); _itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { - if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) + if (string.IsNullOrEmpty(collectionContractAttribute.KeyName)) throw new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))); if (!isDictionary) throw new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)); @@ -470,7 +470,7 @@ private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAtt } if (collectionContractAttribute.IsValueNameSetExplicitly) { - if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) + if (string.IsNullOrEmpty(collectionContractAttribute.ValueName)) throw new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))); if (!isDictionary) throw new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index 01a3a96eee7b7..b3d28299c1d16 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -1313,7 +1313,7 @@ private static XmlQualifiedName GetDCTypeXmlName(Type type, DataContractAttribut if (dataContractAttribute.IsNameSetExplicitly) { name = dataContractAttribute.Name; - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) throw new InvalidDataContractException(SR.Format(SR.InvalidDataContractName, DataContract.GetClrTypeFullName(type))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); @@ -1425,7 +1425,7 @@ internal static XmlQualifiedName GetCollectionXmlName(Type type, Type itemType, if (collectionContractAttribute.IsNameSetExplicitly) { name = collectionContractAttribute.Name; - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) throw new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractName, DataContract.GetClrTypeFullName(type))); if (type.IsGenericType && !type.IsGenericTypeDefinition) name = ExpandGenericParameters(name, type); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs index e8e6c3a6df94d..9b73639c4d1a9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs @@ -236,7 +236,7 @@ private void ImportDataMembers() DataMember memberContract = new DataMember(field); if (memberAttribute.IsValueSetExplicitly) { - if (memberAttribute.Value == null || memberAttribute.Value.Length == 0) + if (string.IsNullOrEmpty(memberAttribute.Value)) ThrowInvalidDataContractException(SR.Format(SR.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type))); memberContract.Name = memberAttribute.Value; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs index b9a545d4cfa0c..c60cc237b71eb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs @@ -269,7 +269,7 @@ internal override ulong ReadContentAsUnsignedLong() { string value = reader.ReadContentAsString(); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64"))); } @@ -302,7 +302,7 @@ internal override ulong ReadElementContentAsUnsignedLong() string value = reader.ReadElementContentAsString(); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) { throw new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, "UInt64"))); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index afd366d024bbc..f0dd2508304ee 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -596,7 +596,7 @@ internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName xmlName, out XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = null; InvokeSchemaProviderMethod(type, schemas, out xmlName, out xsdType, out hasRoot); - if (xmlName.Name == null || xmlName.Name.Length == 0) + if (string.IsNullOrEmpty(xmlName.Name)) throw new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type))); } @@ -620,7 +620,7 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema hasRoot = false; } string? methodName = provider.MethodName; - if (methodName == null || methodName.Length == 0) + if (string.IsNullOrEmpty(methodName)) { if (!provider.IsAny) throw new InvalidDataContractException(SR.Format(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))); @@ -655,7 +655,7 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema { string? typeName = providerXsdType.Name; string? typeNs = null; - if (typeName == null || typeName.Length == 0) + if (string.IsNullOrEmpty(typeName)) { DataContract.GetDefaultXmlName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs); xmlName = new XmlQualifiedName(typeName, typeNs); @@ -702,7 +702,7 @@ private static void InvokeGetSchemaMethod( } else { - if (schema.Id == null || schema.Id.Length == 0) + if (string.IsNullOrEmpty(schema.Id)) throw new InvalidDataContractException(SR.Format(SR.InvalidReturnSchemaOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType))); AddDefaultTypedDatasetType(schemas, schema, xmlName.Name, xmlName.Namespace); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs index 2a632482b459e..431bd3263e2d0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs @@ -43,8 +43,8 @@ internal static class SchemaHelper { internal static bool NamespacesEqual(string? ns1, string? ns2) { - if (ns1 == null || ns1.Length == 0) - return (ns2 == null || ns2.Length == 0); + if (string.IsNullOrEmpty(ns1)) + return string.IsNullOrEmpty(ns2); else return ns1 == ns2; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs index 40b5ffb5114d8..63c7d049bfecb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs @@ -144,7 +144,7 @@ public string XPath public string SetNamespace(string ns) { string? prefix = _namespaces.LookupPrefix(ns); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { prefix = "xg" + (_nextPrefix++).ToString(NumberFormatInfo.InvariantInfo); Namespaces.AddNamespace(prefix, ns); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs index 6017b219bb5d4..a5d6564772104 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs @@ -168,9 +168,9 @@ internal XmlDataContractCriticalHelper( XmlRootAttribute xmlRootAttribute = (XmlRootAttribute)xmlRootAttributes[0]; _isTopLevelElementNullable = xmlRootAttribute.IsNullable; string elementName = xmlRootAttribute.ElementName; - _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); + _topLevelElementName = string.IsNullOrEmpty(elementName) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); string? elementNs = xmlRootAttribute.Namespace; - _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); + _topLevelElementNamespace = string.IsNullOrEmpty(elementNs) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); } else { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index c8ff3273077f8..b04258f0da990 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -1070,7 +1070,7 @@ internal static XmlElement CreateWrapperXmlElement(XmlDocument document, IList(() => XName.Get(null)); Assert.Throws(() => XName.Get(null, "foo")); - Assert.Throws(() => XName.Get(string.Empty, "foo")); + Assert.Throws(() => XName.Get(string.Empty, "foo")); AssertExtensions.Throws("expandedName", () => XName.Get(string.Empty)); AssertExtensions.Throws(null, () => XName.Get("{}")); AssertExtensions.Throws(null, () => XName.Get("{foo}")); diff --git a/src/libraries/System.Private.Xml.Linq/tests/misc/RegressionTests.cs b/src/libraries/System.Private.Xml.Linq/tests/misc/RegressionTests.cs index 77f0ded9a3302..acb946bee68bf 100644 --- a/src/libraries/System.Private.Xml.Linq/tests/misc/RegressionTests.cs +++ b/src/libraries/System.Private.Xml.Linq/tests/misc/RegressionTests.cs @@ -16,7 +16,7 @@ public class RegressionTests public void XPIEmptyStringShouldNotBeAllowed() { var pi = new XProcessingInstruction("PI", "data"); - Assert.Throws(() => pi.Target = string.Empty); + Assert.Throws(() => pi.Target = string.Empty); } [Fact] diff --git a/src/libraries/System.Private.Xml.Linq/tests/misc/XNameAPI.cs b/src/libraries/System.Private.Xml.Linq/tests/misc/XNameAPI.cs index ccc2bf03d70ab..fb874d48674b1 100644 --- a/src/libraries/System.Private.Xml.Linq/tests/misc/XNameAPI.cs +++ b/src/libraries/System.Private.Xml.Linq/tests/misc/XNameAPI.cs @@ -46,13 +46,13 @@ public XName GetName(string name, string ns, GetNameType type) switch (type) { case GetNameType.FromString: - return (ns == null || ns.Length == 0) ? name : "{" + ns + "}" + name; + return string.IsNullOrEmpty(ns) ? name : "{" + ns + "}" + name; case GetNameType.TwoParamGet: return XName.Get(name, ns); case GetNameType.ExpandedName: - return (ns == null || ns.Length == 0) ? XName.Get(name) : XName.Get("{" + ns + "}" + name); + return string.IsNullOrEmpty(ns) ? XName.Get(name) : XName.Get("{" + ns + "}" + name); case GetNameType.XNamespacePlusOperator: - return (ns == null || ns.Length == 0) ? XName.Get(name) : XNamespace.Get(ns) + name; + return string.IsNullOrEmpty(ns) ? XName.Get(name) : XNamespace.Get(ns) + name; default: TestLog.Compare(false, "Test failed: Invalid XName creation method specified"); break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs index 03cc83f4f5fcc..3bc875e90bb3a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlEncodedRawTextWriter.cs @@ -94,7 +94,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str // For the HTML element, it should call this method with ns and prefix as String.Empty public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); _elementScope.Push((byte)_currentElementProperties); @@ -285,7 +285,7 @@ internal override void WriteFullEndElement(string prefix, string localName, stri // public override void WriteStartAttribute(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); if (ns.Length == 0) { @@ -353,7 +353,7 @@ public override void WriteEndAttribute() // HTML PI's use ">" to terminate rather than "?>". public override void WriteProcessingInstruction(string target, string? text) { - Debug.Assert(target != null && target.Length != 0 && text != null); + Debug.Assert(!string.IsNullOrEmpty(target) && text != null); if (_trackTextContent && _inTextContent) { ChangeTextContentMark(false); } @@ -813,7 +813,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); if (_trackTextContent && _inTextContent) { ChangeTextContentMark(false); } @@ -877,7 +877,7 @@ internal override void StartElementContent() internal override void WriteEndElement(string? prefix, string localName, string? ns) { bool isBlockWs; - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); _indentLevel--; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlRawTextWriterGenerator.ttinclude b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlRawTextWriterGenerator.ttinclude index 5b0986a4ac2e0..c449d772fa635 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlRawTextWriterGenerator.ttinclude +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlRawTextWriterGenerator.ttinclude @@ -97,7 +97,7 @@ namespace System.Xml // For the HTML element, it should call this method with ns and prefix as String.Empty public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); _elementScope.Push((byte)_currentElementProperties); @@ -288,7 +288,7 @@ namespace System.Xml // public override void WriteStartAttribute(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); if (ns.Length == 0) { @@ -356,7 +356,7 @@ namespace System.Xml // HTML PI's use ">" to terminate rather than "?>". public override void WriteProcessingInstruction(string target, string? text) { - Debug.Assert(target != null && target.Length != 0 && text != null);<# + Debug.Assert(!string.IsNullOrEmpty(target) && text != null);<# #><#= SetTextContentMark(3, false) #> @@ -825,7 +825,7 @@ namespace System.Xml public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null);<# + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null);<# #><#= SetTextContentMark(3, false) #> @@ -889,7 +889,7 @@ namespace System.Xml internal override void WriteEndElement(string? prefix, string localName, string? ns) { bool isBlockWs; - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); _indentLevel--; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs index 70ce7f6774011..23f48e562368e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs @@ -87,7 +87,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str // For the HTML element, it should call this method with ns and prefix as String.Empty public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); _elementScope.Push((byte)_currentElementProperties); @@ -272,7 +272,7 @@ internal override void WriteFullEndElement(string prefix, string localName, stri // public override void WriteStartAttribute(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); if (ns.Length == 0) { @@ -336,7 +336,7 @@ public override void WriteEndAttribute() // HTML PI's use ">" to terminate rather than "?>". public override void WriteProcessingInstruction(string target, string? text) { - Debug.Assert(target != null && target.Length != 0 && text != null); + Debug.Assert(!string.IsNullOrEmpty(target) && text != null); _bufBytes[base._bufPos++] = (byte)'<'; _bufBytes[base._bufPos++] = (byte)'?'; @@ -785,7 +785,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); base._elementScope.Push((byte)base._currentElementProperties); @@ -847,7 +847,7 @@ internal override void StartElementContent() internal override void WriteEndElement(string? prefix, string localName, string? ns) { bool isBlockWs; - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); _indentLevel--; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index f16e3b69d2b2d..f015e77cc4ebb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -109,10 +109,7 @@ public override void WriteStartElement(string? prefix, string localName, string? { if (_checkNames) { - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); ValidateNCName(localName); @@ -129,10 +126,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin { if (_checkNames) { - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); ValidateNCName(localName); @@ -296,10 +290,7 @@ public override void WriteNmToken(string name) { if (_checkNames) { - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); XmlConvert.VerifyNMTOKEN(name); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs index eee4b81c1ed2a..35a3bca99b09f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs @@ -60,10 +60,7 @@ public override Task WriteStartElementAsync(string? prefix, string localName, st { if (_checkNames) { - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); ValidateNCName(localName); @@ -79,10 +76,7 @@ protected internal override Task WriteStartAttributeAsync(string? prefix, string { if (_checkNames) { - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); ValidateNCName(localName); @@ -243,10 +237,7 @@ public override Task WriteNmTokenAsync(string name) { if (_checkNames) { - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); XmlConvert.VerifyNMTOKEN(name); } return writer.WriteNmTokenAsync(name); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs index 508a8fa50abbe..f4126fcf9407e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs @@ -297,7 +297,7 @@ public override void WriteStartElement(string? prefix, string localName, string? if (_trackTextContent && _inTextContent) { ChangeTextContentMark(false); } _bufChars[_bufPos++] = (char)'<'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); _bufChars[_bufPos++] = (char)':'; @@ -334,7 +334,7 @@ internal override void WriteEndElement(string prefix, string localName, string n _bufChars[_bufPos++] = (char)'<'; _bufChars[_bufPos++] = (char)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); _bufChars[_bufPos++] = (char)':'; @@ -363,7 +363,7 @@ internal override void WriteFullEndElement(string prefix, string localName, stri _bufChars[_bufPos++] = (char)'<'; _bufChars[_bufPos++] = (char)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); _bufChars[_bufPos++] = (char)':'; @@ -1960,7 +1960,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Add indentation if (!_mixedContent && base._textPos != base._bufPos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs index 6ca97ede3105e..d15b7680b248a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs @@ -181,7 +181,7 @@ public override Task WriteStartElementAsync(string? prefix, string localName, st Task task; _bufChars[_bufPos++] = (char)'<'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { task = RawTextAsync(prefix, ":", localName); } @@ -213,7 +213,7 @@ internal override Task WriteEndElementAsync(string prefix, string localName, str _bufChars[_bufPos++] = (char)'<'; _bufChars[_bufPos++] = (char)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return RawTextAsync(prefix, ":", localName, ">"); } @@ -245,7 +245,7 @@ internal override Task WriteFullEndElementAsync(string prefix, string localName, _bufChars[_bufPos++] = (char)'<'; _bufChars[_bufPos++] = (char)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return RawTextAsync(prefix, ":", localName, ">"); } @@ -1919,7 +1919,7 @@ public override async Task WriteDocTypeAsync(string name, string? pubid, string? public override async Task WriteStartElementAsync(string? prefix, string localName, string? ns) { CheckAsyncCall(); - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Add indentation if (!_mixedContent && base._textPos != base._bufPos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude index 61d85043919b0..3c0837cbc6dcd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude @@ -325,7 +325,7 @@ namespace System.Xml #><#= SetTextContentMark(3, false) #> <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'<'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); <#= BufferName #>[_bufPos++] = (<#= BufferType #>)':'; @@ -362,7 +362,7 @@ namespace System.Xml <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'<'; <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); <#= BufferName #>[_bufPos++] = (<#= BufferType #>)':'; @@ -391,7 +391,7 @@ namespace System.Xml <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'<'; <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); <#= BufferName #>[_bufPos++] = (<#= BufferType #>)':'; @@ -2013,7 +2013,7 @@ namespace System.Xml public override void WriteStartElement(string prefix, string localName, string ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Add indentation if (!_mixedContent && base._textPos != base._bufPos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude index 638ee0f401e67..86c3127b60186 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude @@ -184,7 +184,7 @@ namespace System.Xml Task task; <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'<'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { task = RawTextAsync(prefix, ":", localName); } @@ -216,7 +216,7 @@ namespace System.Xml <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'<'; <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return RawTextAsync(prefix, ":", localName, ">"); } @@ -248,7 +248,7 @@ namespace System.Xml <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'<'; <#= BufferName #>[_bufPos++] = (<#= BufferType #>)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return RawTextAsync(prefix, ":", localName, ">"); } @@ -1862,7 +1862,7 @@ namespace System.Xml public override async Task WriteStartElementAsync(string prefix, string localName, string ns) { CheckAsyncCall(); - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Add indentation if (!_mixedContent && base._textPos != base._bufPos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index bb6b6170c21ed..4de62beab8966 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -463,7 +463,7 @@ internal XmlTextReaderImpl(string? url, Stream input, XmlNameTable nt) : this(nt ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null); _namespaceManager = new XmlNamespaceManager(nt); - if (url == null || url.Length == 0) + if (string.IsNullOrEmpty(url)) { InitStreamInput(input, null); } @@ -506,7 +506,7 @@ internal XmlTextReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserCo : this((context != null && context.NameTable != null) ? context.NameTable : new NameTable()) { Encoding? enc = context?.Encoding; - if (context == null || context.BaseURI == null || context.BaseURI.Length == 0) + if (context == null || string.IsNullOrEmpty(context.BaseURI)) { InitStreamInput(xmlFragment, enc); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index 95f9f2b8c3bca..1ed5742fa5722 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -495,7 +495,7 @@ public override void WriteStartElement(string? prefix, string localName, string? if (ns == null) { // use defined prefix - if (prefix != null && prefix.Length != 0 && (LookupNamespace(prefix) == -1)) + if (!string.IsNullOrEmpty(prefix) && (LookupNamespace(prefix) == -1)) { throw new ArgumentException(SR.Xml_UndefPrefix); } @@ -530,7 +530,7 @@ public override void WriteStartElement(string? prefix, string localName, string? } } _stack[_top].prefix = null; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { _stack[_top].prefix = prefix; _textWriter.Write(prefix); @@ -539,7 +539,7 @@ public override void WriteStartElement(string? prefix, string localName, string? } else { - if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) + if (!string.IsNullOrEmpty(ns) || !string.IsNullOrEmpty(prefix)) { throw new ArgumentException(SR.Xml_NoNamespaces); } @@ -610,7 +610,7 @@ and not really insist on a specific value. Who knows in the future it throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs); } - if (localName == null || localName.Length == 0) + if (string.IsNullOrEmpty(localName)) { localName = prefix; prefix = null; @@ -671,7 +671,7 @@ and not really insist on a specific value. Who knows in the future it } } - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { _textWriter.Write(prefix); _textWriter.Write(':'); @@ -679,7 +679,7 @@ and not really insist on a specific value. Who knows in the future it } else { - if ((ns != null && ns.Length != 0) || (prefix != null && prefix.Length != 0)) + if (!string.IsNullOrEmpty(ns) || !string.IsNullOrEmpty(prefix)) { throw new ArgumentException(SR.Xml_NoNamespaces); } @@ -1058,7 +1058,7 @@ public override void WriteQualifiedName(string localName, string? ns) AutoComplete(Token.Content); if (_namespaces) { - if (ns != null && ns.Length != 0 && ns != _stack[_top].defaultNs) + if (!string.IsNullOrEmpty(ns) && ns != _stack[_top].defaultNs) { string? prefix = FindPrefix(ns); if (prefix == null) @@ -1079,7 +1079,7 @@ public override void WriteQualifiedName(string localName, string? ns) } } } - else if (ns != null && ns.Length != 0) + else if (!string.IsNullOrEmpty(ns)) { throw new ArgumentException(SR.Xml_NoNamespaces); } @@ -1096,10 +1096,7 @@ public override void WriteQualifiedName(string localName, string? ns) // Returns the closest prefix defined in the current namespace scope for the specified namespace URI. public override string? LookupPrefix(string ns) { - if (ns == null || ns.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(ns); string? s = FindPrefix(ns); if (s == null && ns == _stack[_top].defaultNs) @@ -1150,10 +1147,7 @@ public override void WriteNmToken(string name) { AutoComplete(Token.Content); - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); if (!ValidateNames.IsNmtokenNoNamespaces(name)) { throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name)); @@ -1692,10 +1686,7 @@ private void InternalWriteName(string name, bool isNCName) // all valid name characters at that position. This can't be changed because of backwards compatibility. private void ValidateName(string name, bool isNCName) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); int nameLength = name.Length; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs index 6f5ada6cab1f9..be109c7ce0d48 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs @@ -239,7 +239,7 @@ public override void WriteStartElement(string? prefix, string localName, string? Debug.Assert(prefix != null); _bufBytes[_bufPos++] = (byte)'<'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); _bufBytes[_bufPos++] = (byte)':'; @@ -274,7 +274,7 @@ internal override void WriteEndElement(string prefix, string localName, string n _bufBytes[_bufPos++] = (byte)'<'; _bufBytes[_bufPos++] = (byte)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); _bufBytes[_bufPos++] = (byte)':'; @@ -301,7 +301,7 @@ internal override void WriteFullEndElement(string prefix, string localName, stri _bufBytes[_bufPos++] = (byte)'<'; _bufBytes[_bufPos++] = (byte)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { RawText(prefix); _bufBytes[_bufPos++] = (byte)':'; @@ -1817,7 +1817,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Add indentation if (!_mixedContent && base._textPos != base._bufPos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs index 09d68c92ecb9a..b12404bfb9988 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs @@ -155,7 +155,7 @@ public override Task WriteStartElementAsync(string? prefix, string localName, st Task task; _bufBytes[_bufPos++] = (byte)'<'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { task = RawTextAsync(prefix, ":", localName); } @@ -185,7 +185,7 @@ internal override Task WriteEndElementAsync(string prefix, string localName, str _bufBytes[_bufPos++] = (byte)'<'; _bufBytes[_bufPos++] = (byte)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return RawTextAsync(prefix, ":", localName, ">"); } @@ -215,7 +215,7 @@ internal override Task WriteFullEndElementAsync(string prefix, string localName, _bufBytes[_bufPos++] = (byte)'<'; _bufBytes[_bufPos++] = (byte)'/'; - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return RawTextAsync(prefix, ":", localName, ">"); } @@ -1784,7 +1784,7 @@ public override async Task WriteDocTypeAsync(string name, string? pubid, string? public override async Task WriteStartElementAsync(string? prefix, string localName, string? ns) { CheckAsyncCall(); - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Add indentation if (!_mixedContent && base._textPos != base._bufPos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs index fb9c148bcdb54..bb6d8f8337c9f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs @@ -1013,7 +1013,7 @@ private void ParseDtdFromParserContext() Debug.Assert(_parserContext != null); Debug.Assert(_coreReaderImpl.DtdInfo == null); - if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0) + if (string.IsNullOrEmpty(_parserContext.DocTypeName)) { return; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs index 9064713526146..f30ffd5b3da0b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs @@ -176,7 +176,7 @@ private async Task ParseDtdFromParserContextAsync() Debug.Assert(_parserContext != null); Debug.Assert(_coreReaderImpl.DtdInfo == null); - if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0) + if (string.IsNullOrEmpty(_parserContext.DocTypeName)) { return; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs index c6c64a92b35ff..d47ed8d3a9aac 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs @@ -360,10 +360,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str { try { - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); XmlConvert.VerifyQName(name, ExceptionType.XmlException); if (_conformanceLevel == ConformanceLevel.Fragment) @@ -428,10 +425,7 @@ public override void WriteStartElement(string? prefix, string localName, string? try { // check local name - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); CheckNCName(localName); AdvanceState(Token.StartElement); @@ -607,7 +601,7 @@ public override void WriteStartAttribute(string? prefix, string? localName, stri try { // check local name - if (localName == null || localName.Length == 0) + if (string.IsNullOrEmpty(localName)) { if (prefix == "xmlns") { @@ -660,7 +654,7 @@ public override void WriteStartAttribute(string? prefix, string? localName, stri else if (namespaceName.Length > 0) { prefix = LookupPrefix(namespaceName); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { prefix = GeneratePrefix(); } @@ -892,10 +886,7 @@ public override void WriteProcessingInstruction(string name, string? text) try { // check name - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); CheckNCName(name); // check text @@ -940,10 +931,7 @@ public override void WriteEntityRef(string name) try { // check name - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); CheckNCName(name); AdvanceState(Token.Text); @@ -1291,15 +1279,12 @@ public override void WriteQualifiedName(string localName, string? ns) { try { - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); CheckNCName(localName); AdvanceState(Token.Text); string? prefix = string.Empty; - if (ns != null && ns.Length != 0) + if (!string.IsNullOrEmpty(ns)) { prefix = LookupPrefix(ns); if (prefix == null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs index efc1ae2bab659..1c506e61ec4e9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs @@ -61,10 +61,7 @@ public override async Task WriteDocTypeAsync(string name, string? pubid, string? { try { - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); XmlConvert.VerifyQName(name, ExceptionType.XmlException); @@ -183,10 +180,7 @@ public override Task WriteStartElementAsync(string? prefix, string localName, st try { // check local name - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartElement); @@ -448,7 +442,7 @@ protected internal override Task WriteStartAttributeAsync(string? prefix, string try { // check local name - if (localName == null || localName.Length == 0) + if (string.IsNullOrEmpty(localName)) { if (prefix == "xmlns") { @@ -519,7 +513,7 @@ private Task WriteStartAttributeAsync_NoAdvanceState(string? prefix, string loca else if (namespaceName.Length > 0) { prefix = LookupPrefix(namespaceName); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { prefix = GeneratePrefix(); } @@ -794,10 +788,7 @@ public override async Task WriteProcessingInstructionAsync(string name, string? try { // check name - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); CheckNCName(name); // check text @@ -842,11 +833,7 @@ public override async Task WriteEntityRefAsync(string name) try { // check name - if (name == null || name.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName); - } - + ArgumentException.ThrowIfNullOrEmpty(name); CheckNCName(name); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); @@ -1144,15 +1131,12 @@ public override async Task WriteQualifiedNameAsync(string localName, string? ns) { try { - if (localName == null || localName.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(localName); CheckNCName(localName); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); string? prefix = string.Empty; - if (ns != null && ns.Length != 0) + if (!string.IsNullOrEmpty(ns)) { prefix = LookupPrefix(ns); if (prefix == null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs index 52226efff375d..4c57c78423af0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs @@ -212,10 +212,7 @@ public virtual void Close() { } // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual void WriteNmToken(string name) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); WriteString(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs index a2bc43bfa0a5c..990a7e8b3df4e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs @@ -198,10 +198,7 @@ public virtual Task FlushAsync() // (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name). public virtual Task WriteNmTokenAsync(string name) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException(SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); return WriteStringAsync(XmlConvert.VerifyNMTOKEN(name, ExceptionType.ArgumentException)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index 313fcbaf4fafa..b3298550abe4d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -242,7 +242,7 @@ public override string Name { Debug.Assert(_cachedNode != null); string? prefix = _validator.GetDefaultAttributePrefix(_cachedNode.Namespace); - if (prefix != null && prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { return $"{prefix}:{_cachedNode.LocalName}"; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index 558212ac16646..ab4e98aaa85d1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -364,21 +364,21 @@ private void InitDecAttr() { int i = 0; string? strTemp = _doc.Version; - if (strTemp != null && strTemp.Length != 0) + if (!string.IsNullOrEmpty(strTemp)) { decNodeAttributes[i].name = strVersion; decNodeAttributes[i].value = strTemp; i++; } strTemp = _doc.Encoding; - if (strTemp != null && strTemp.Length != 0) + if (!string.IsNullOrEmpty(strTemp)) { decNodeAttributes[i].name = strEncoding; decNodeAttributes[i].value = strTemp; i++; } strTemp = _doc.Standalone; - if (strTemp != null && strTemp.Length != 0) + if (!string.IsNullOrEmpty(strTemp)) { decNodeAttributes[i].name = strStandalone; decNodeAttributes[i].value = strTemp; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs index b4e3e78ef3eaf..6a56af8592e9a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs @@ -16,12 +16,7 @@ public class XmlProcessingInstruction : XmlLinkedNode protected internal XmlProcessingInstruction(string target, string? data, XmlDocument doc) : base(doc) { - ArgumentNullException.ThrowIfNull(target); - - if (target.Length == 0) - { - throw new ArgumentException(SR.Xml_EmptyName, nameof(target)); - } + ArgumentException.ThrowIfNullOrEmpty(target); _target = target; _data = data ?? string.Empty; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs index 6453243fb64ff..d24b86f64e303 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs @@ -1879,7 +1879,7 @@ internal override int Compare(object value1, object value2) Exception? exception; typedValue = null; - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } @@ -1910,7 +1910,7 @@ internal sealed class Datatype_yearMonthDuration : Datatype_duration Exception? exception; typedValue = null; - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } @@ -1949,7 +1949,7 @@ internal sealed class Datatype_dayTimeDuration : Datatype_duration typedValue = null; - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } @@ -2704,7 +2704,7 @@ internal override RestrictionFlags ValidRestrictionFlags typedValue = null; - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } @@ -3037,7 +3037,7 @@ internal override RestrictionFlags ValidRestrictionFlags typedValue = null; - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } @@ -3735,7 +3735,7 @@ internal sealed class Datatype_QNameXdr : Datatype_anySimpleType public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { throw new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs index ad0484beba705..36cf113ab0957 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs @@ -1452,7 +1452,7 @@ private static bool MatchEnumeration(string value, ArrayList enumeration, XmlSch break; case XmlTypeCode.Language: - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return new XmlSchemaException(SR.Sch_EmptyAttributeValue, string.Empty); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index 78951fd91b0a4..3d994386a83f0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -113,7 +113,7 @@ public bool Execute(XmlSchema schema, string? targetNamespace, bool loadExternal SendValidationEvent(SR.Sch_MismatchTargetNamespaceEx, targetNamespace, _rootSchema.TargetNamespace, _rootSchema); } } - else if (targetNamespace != null && targetNamespace.Length != 0) + else if (!string.IsNullOrEmpty(targetNamespace)) { //if schema.TargetNamespace == null & targetNamespace != null, we will force the schema components into targetNamespace _rootSchema = GetChameleonSchema(targetNamespace, _rootSchema); //Chameleon include at top-level } @@ -632,7 +632,7 @@ private void Preprocess(XmlSchema schema, string? targetNamespace, ArrayList imp SendValidationEvent(SR.Sch_MismatchTargetNamespaceInclude, externalSchema.TargetNamespace, schema.TargetNamespace, include); } } - else if (targetNamespace != null && targetNamespace.Length != 0) + else if (!string.IsNullOrEmpty(targetNamespace)) { //Chameleon redefine externalSchema = GetChameleonSchema(targetNamespace, externalSchema); include.Schema = externalSchema; //Reset the schema property to the cloned schema @@ -2073,7 +2073,7 @@ private void ValidateIdAttribute(XmlSchemaObject xso) private void ValidateNameAttribute(XmlSchemaObject xso) { string? name = xso.NameAttribute; - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) { SendValidationEvent(SR.Sch_InvalidNameAttributeEx, null, SR.Sch_NullValue, xso); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs index d9fefe7799817..f4b835cf4bab1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs @@ -1733,7 +1733,7 @@ private void ValidateIdAttribute(XmlSchemaObject xso) private void ValidateNameAttribute(XmlSchemaObject xso) { string? name = xso.NameAttribute; - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) { SendValidationEvent(SR.Sch_InvalidNameAttributeEx, null, SR.Sch_NullValue, xso); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index 69c143f0175fb..fe2e510c3812c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -174,7 +174,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) { ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); - if (_targetNs != null && _targetNs.Length != 0) + if (!string.IsNullOrEmpty(_targetNs)) { ns.Add("tns", _targetNs); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs index 988cc27a3332b..8eb642d5e6f5b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs @@ -38,7 +38,7 @@ internal string ResolvedNamespace { get { - if (_ns == null || _ns.Length == 0) + if (string.IsNullOrEmpty(_ns)) { return "##any"; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs index c9502b79877bb..e817e1965362e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs @@ -95,7 +95,7 @@ internal XmlResolver? XmlResolver /// public XmlSchema? Add(string? ns, [StringSyntax(StringSyntaxAttribute.Uri)] string uri) { - if (uri == null || uri.Length == 0) + if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException(nameof(uri)); XmlTextReader reader = new XmlTextReader(uri, _nameTable); reader.XmlResolver = _xmlResolver; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs index 93e4870b03a3a..39308b0e9b8fb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs @@ -218,7 +218,7 @@ internal Hashtable SchemaLocations /// public XmlSchema? Add(string? targetNamespace, string schemaUri) { - if (schemaUri == null || schemaUri.Length == 0) + if (string.IsNullOrEmpty(schemaUri)) { throw new ArgumentNullException(nameof(schemaUri)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 40774f4335c14..e2eabb8a0c711 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -1025,7 +1025,7 @@ internal void GetUnspecifiedDefaultAttributes(ArrayList defaultAttributes, bool if (attributeNS.Length > 0) { defaultPrefix = GetDefaultAttributePrefix(attributeNS); - if (defaultPrefix == null || defaultPrefix.Length == 0) + if (string.IsNullOrEmpty(defaultPrefix)) { SendValidationEvent(SR.Sch_DefaultAttributeNotApplied, new string[2] { attdef.Name.ToString(), QNameString(_context.LocalName!, _context.Namespace!) }); continue; 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 3d2d3c38b51dd..b7f21e4809517 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 @@ -254,7 +254,7 @@ internal static string GetTypeName(string name, CodeDomProvider codeProvider) { private static void EscapeKeywords(string identifier, StringBuilder sb) { - if (identifier == null || identifier.Length == 0) + if (string.IsNullOrEmpty(identifier)) return; int arrayCount = 0; while (identifier.EndsWith("[]", StringComparison.Ordinal)) @@ -279,7 +279,7 @@ private static void EscapeKeywords(string identifier, StringBuilder sb) [return: NotNullIfNotNull(nameof(identifier))] private static string? EscapeKeywords(string? identifier) { - if (identifier == null || identifier.Length == 0) return identifier; + if (string.IsNullOrEmpty(identifier)) return identifier; string originalIdentifier = identifier; string[] names = identifier.Split(s_identifierSeparators); StringBuilder sb = new StringBuilder(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index ac3ee4732b88a..2daa8020dc598 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -103,14 +103,14 @@ internal bool IsTopLevelInSchema [return: NotNullIfNotNull(nameof(name))] internal static string? EscapeName(string? name) { - if (name == null || name.Length == 0) return name; + if (string.IsNullOrEmpty(name)) return name; return XmlConvert.EncodeLocalName(name); } [return: NotNullIfNotNull(nameof(name))] internal static string? EscapeQName(string? name) { - if (name == null || name.Length == 0) return name; + if (string.IsNullOrEmpty(name)) return name; int colon = name.LastIndexOf(':'); if (colon < 0) return XmlConvert.EncodeLocalName(name); @@ -341,7 +341,7 @@ internal bool IsReference [MemberNotNullWhen(false, nameof(_typeName))] internal bool IsAnonymousType { - get { return _typeName == null || _typeName.Length == 0; } + get { return string.IsNullOrEmpty(_typeName); } } internal virtual string DefaultElementName @@ -1347,7 +1347,7 @@ private void RetrieveSerializableSchema() if (_schema != null) { - if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type!.FullName)); + if (string.IsNullOrEmpty(_schema.Id)) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type!.FullName)); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index 6ca7f3ff1da72..8355612e9f9ed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -1646,7 +1646,7 @@ void Wrapper(object? collection, object? collectionItems) // find anyElement if present. for (int j = 0; j < mapping.Elements!.Length; j++) { - if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) + if (mapping.Elements[j].Any && string.IsNullOrEmpty(mapping.Elements[j].Name)) { anyElement = mapping; break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 49ce530633c3e..178591cc6dcc2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -1068,8 +1068,7 @@ private static bool IsDefaultValue(object o, object value) { if (value is string && ((string)value).Length == 0) { - string str = (string)o; - return str == null || str.Length == 0; + return string.IsNullOrEmpty((string)o); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs index 9bedc6dc0ce20..5d2d6175ebd35 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs @@ -160,11 +160,11 @@ private void WriteIndent() } private void WriteAttribute(string localName, string ns, string? value) { - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) return; _w.Append(','); _w.Append(ns); - if (ns != null && ns.Length != 0) + if (!string.IsNullOrEmpty(ns)) _w.Append(':'); _w.Append(localName); _w.Append('='); @@ -304,7 +304,7 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o) WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) { - if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) + if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && !string.IsNullOrEmpty(o.QualifiedName.Namespace)) { WriteAttribute(@"form", @"", "qualified"); } @@ -982,7 +982,7 @@ private void Write46_XmlSchemaElement(XmlSchemaElement? o) WriteAttribute(@"fixed", @"", o.FixedValue); if (o.Parent != null && !(o.Parent is XmlSchema)) { - if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) + if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && !string.IsNullOrEmpty(o.QualifiedName.Namespace)) { WriteAttribute(@"form", @"", "qualified"); } @@ -991,7 +991,7 @@ private void Write46_XmlSchemaElement(XmlSchemaElement? o) WriteAttribute(@"form", @"", "unqualified"); } } - if (o.Name != null && o.Name.Length != 0) + if (!string.IsNullOrEmpty(o.Name)) { WriteAttribute(@"name", @"", o.Name); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index a4f5aab5fbc3c..eb22438a6d8cc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -122,7 +122,7 @@ public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, X ArgumentNullException.ThrowIfNull(members); ElementAccessor element = new ElementAccessor(); element.IsSoap = true; - element.Name = elementName == null || elementName.Length == 0 ? elementName : XmlConvert.EncodeLocalName(elementName); + element.Name = string.IsNullOrEmpty(elementName) ? elementName : XmlConvert.EncodeLocalName(elementName); element.Mapping = ImportMembersMapping(members, ns, hasWrapperElement, writeAccessors, validate, new RecursionLimiter()); element.Mapping.TypeName = elementName; @@ -729,7 +729,7 @@ private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; - element.Name = mapping.TypeName; //XmlConvert.EncodeLocalName(name == null || name.Length == 0 ? mapping.TypeName : name); + element.Name = mapping.TypeName; element.Namespace = ns; element.Mapping = mapping; return element; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs index 4c49553473bd3..c6925ffce5483 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs @@ -98,7 +98,7 @@ public XmlAttributes(ICustomAttributeProvider provider) } else if (attrs[i] is XmlAnyElementAttribute any) { - if ((any.Name == null || any.Name.Length == 0) && any.GetNamespaceSpecified() && any.Namespace == null) + if (string.IsNullOrEmpty(any.Name) && any.GetNamespaceSpecified() && any.Namespace == null) { // ignore duplicate wildcards wildcard = any; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 1a6cb23c883fd..b0a635014cb6f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -207,7 +207,7 @@ public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, X public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, XmlMappingAccess access) { ElementAccessor element = new ElementAccessor(); - element.Name = elementName == null || elementName.Length == 0 ? elementName : XmlConvert.EncodeLocalName(elementName); + element.Name = string.IsNullOrEmpty(elementName) ? elementName : XmlConvert.EncodeLocalName(elementName); element.Namespace = ns; MembersMapping membersMapping = ImportMembersMapping(members, ns, hasWrapperElement, rpc, openModel, new RecursionLimiter()); @@ -696,7 +696,7 @@ private StructMapping GetRootMapping() private TypeMapping? GetTypeMapping(string? typeName, string? ns, TypeDesc typeDesc, NameTable typeLib, Type? type) { TypeMapping? mapping; - if (typeName == null || typeName.Length == 0) + if (string.IsNullOrEmpty(typeName)) mapping = type == null ? null : (TypeMapping?)_anonymous[type]; else mapping = (TypeMapping?)typeLib[typeName, ns]; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index a05f5a56fb092..5d885f37accda 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -313,8 +313,8 @@ private void AddSchemaImport(string? ns, string? referencingNs) private static bool NamespacesEqual(string? ns1, string? ns2) { - if (ns1 == null || ns1.Length == 0) - return (ns2 == null || ns2.Length == 0); + if (string.IsNullOrEmpty(ns1)) + return string.IsNullOrEmpty(ns2); else return ns1 == ns2; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index c6efc6548ea51..1545ad4144785 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -444,7 +444,7 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) { mapping = ImportStructType(type, typeNs, identifier, baseType, false); - if (mapping != null && type.Name != null && type.Name.Length != 0) + if (mapping != null && !string.IsNullOrEmpty(type.Name)) ImportDerivedTypes(new XmlQualifiedName(identifier, typeNs)); } return mapping; @@ -533,10 +533,10 @@ private StructMapping ImportStructType(XmlSchemaType type, string? typeNs, strin } identifier = Accessor.UnescapeName(identifier); - string typeName = type.Name == null || type.Name.Length == 0 ? GenerateUniqueTypeName(identifier, typeNs) : GenerateUniqueTypeName(identifier); + string typeName = string.IsNullOrEmpty(type.Name) ? GenerateUniqueTypeName(identifier, typeNs) : GenerateUniqueTypeName(identifier); structMapping.TypeDesc = new TypeDesc(typeName, typeName, TypeKind.Struct, baseTypeDesc, flags); structMapping.Namespace = typeNs; - structMapping.TypeName = type.Name == null || type.Name.Length == 0 ? null : identifier; + structMapping.TypeName = string.IsNullOrEmpty(type.Name) ? null : identifier; structMapping.BaseMapping = (StructMapping)baseMapping; if (!arrayLike) ImportedMappings.Add(type, structMapping); @@ -1260,7 +1260,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? if (choiceMember.ChoiceIdentifier != null) return null; arrayMapping.TypeDesc = choiceMember.TypeDesc; arrayMapping.Elements = choiceMember.Elements; - arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? $"ArrayOf{CodeIdentifier.MakePascal(arrayMapping.TypeDesc!.Name)}" : type.Name; + arrayMapping.TypeName = string.IsNullOrEmpty(type.Name) ? $"ArrayOf{CodeIdentifier.MakePascal(arrayMapping.TypeDesc!.Name)}" : type.Name; } else if (item is XmlSchemaAll || item is XmlSchemaSequence) { @@ -1277,7 +1277,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? return null; arrayMapping.Elements = new ElementAccessor[] { itemAccessor }; arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping!).TypeDesc!.CreateArrayTypeDesc(); - arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? $"ArrayOf{CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeDesc.Name)}" : type.Name; + arrayMapping.TypeName = string.IsNullOrEmpty(type.Name) ? $"ArrayOf{CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeDesc.Name)}" : type.Name; } else { @@ -1289,7 +1289,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? // for the array-like mappings we need to create a struct mapping for the case when it referenced by the top-level element arrayMapping.TopLevelMapping = ImportStructType(type, ns, identifier, null, true); arrayMapping.TopLevelMapping.ReferencedByTopLevelElement = true; - if (type.Name != null && type.Name.Length != 0) + if (!string.IsNullOrEmpty(type.Name)) ImportDerivedTypes(new XmlQualifiedName(identifier, ns)); return arrayMapping; @@ -1798,7 +1798,7 @@ private PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType, T { PrimitiveMapping? mapping = null; TypeDesc? typeDesc; - if (dataType.Name != null && dataType.Name.Length != 0) + if (!string.IsNullOrEmpty(dataType.Name)) { typeDesc = TypeScope.GetTypeDesc(dataType.Name, ns, flags); if (typeDesc != null) @@ -1853,7 +1853,7 @@ internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags) { TypeDesc? typeDesc; - if (dataType.Name != null && dataType.Name.Length != 0) + if (!string.IsNullOrEmpty(dataType.Name)) { typeDesc = TypeScope.GetTypeDesc(dataType); if (typeDesc != null) return typeDesc; @@ -1949,14 +1949,14 @@ private static XmlSchemaForm ElementForm(string? ns, XmlSchemaElement element) if (schema != null) { - if (ns == null || ns.Length == 0) + if (string.IsNullOrEmpty(ns)) { return schema.ElementFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.ElementFormDefault; } else { XmlSchemas.Preprocess(schema); - return element.QualifiedName.Namespace == null || element.QualifiedName.Namespace.Length == 0 ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; + return string.IsNullOrEmpty(element.QualifiedName.Namespace) ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; } } return XmlSchemaForm.Qualified; @@ -1976,14 +1976,14 @@ private static XmlSchemaForm AttributeForm(string? ns, XmlSchemaAttribute attrib XmlSchema? schema = parent as XmlSchema; if (schema != null) { - if (ns == null || ns.Length == 0) + if (string.IsNullOrEmpty(ns)) { return schema.AttributeFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.AttributeFormDefault; } else { XmlSchemas.Preprocess(schema); - return attribute.QualifiedName.Namespace == null || attribute.QualifiedName.Namespace.Length == 0 ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; + return string.IsNullOrEmpty(attribute.QualifiedName.Namespace) ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; } } return XmlSchemaForm.Unqualified; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index c8ff8e95cdd2a..90e3dd8fd712d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -468,7 +468,7 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { if (item.Parent is XmlSchemaType type) { - if (type.Name != null && type.Name.Length != 0) + if (!string.IsNullOrEmpty(type.Name)) { return type.QualifiedName; } @@ -489,7 +489,7 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) { o = o.Parent; } - if (ns == null || ns.Length == 0) + if (string.IsNullOrEmpty(ns)) { XmlSchemaObject tmp = o; while (tmp.Parent != null) @@ -512,7 +512,7 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) } else if (o is XmlSchemaElement e) { - if (e.Name == null || e.Name.Length == 0) + if (string.IsNullOrEmpty(e.Name)) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); // Element reference '{0}' declared in schema type '{1}' from namespace '{2}' @@ -533,7 +533,7 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) } else if (o is XmlSchemaAttribute a) { - if (a.Name == null || a.Name.Length == 0) + if (string.IsNullOrEmpty(a.Name)) { XmlQualifiedName parentName = XmlSchemas.GetParentName(o); // Attribure reference '{0}' declared in schema type '{1}' from namespace '{2}' 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 93f538f840503..2dc31bd393024 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 @@ -1147,7 +1147,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string? value, bool decodeName) prefix = XmlConvert.DecodeName(prefix); localName = XmlConvert.DecodeName(localName); } - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { return new XmlQualifiedName(_r.NameTable.Add(value), _r.LookupNamespace(string.Empty)); } @@ -1375,7 +1375,7 @@ protected Array EnsureArrayIndex(Array? a, int index, Type elementType) string str = _r.ReadString(); if (str != null && trim) str = str.Trim(); - if (value == null || value.Length == 0) + if (string.IsNullOrEmpty(value)) return str; return value + str; } @@ -3319,7 +3319,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) // find anyElement if present. for (int j = 0; j < mapping.Elements!.Length; j++) { - if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) + if (mapping.Elements[j].Any && string.IsNullOrEmpty(mapping.Elements[j].Name)) { anyElement = member; break; @@ -3979,7 +3979,7 @@ private static string ExpectedElements(Member[] members) { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; - if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; + if (e.Any && string.IsNullOrEmpty(e.Name)) continue; if (!firstElement) qnames += ", "; @@ -4198,7 +4198,7 @@ private void WriteMemberElementsIf(Member[] members, Member? anyElement, string { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; - if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; + if (!isSequence && e.Any && string.IsNullOrEmpty(e.Name)) continue; if (!isSequence) { if (firstElement && count == 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 50a2c73c72c41..de61c280637a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1566,7 +1566,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) // find anyElement if present. for (int j = 0; j < mapping.Elements!.Length; j++) { - if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) + if (mapping.Elements[j].Any && string.IsNullOrEmpty(mapping.Elements[j].Name)) { anyElement = member; break; @@ -2231,7 +2231,7 @@ private static string ExpectedElements(Member[] members) { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; - if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; + if (e.Any && string.IsNullOrEmpty(e.Name)) continue; if (!firstElement) qnames += ", "; @@ -2495,7 +2495,7 @@ private void WriteMemberElementsIf(Member[] members, Member? anyElement, string { ElementAccessor e = elements[j]; string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; - if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; + if (!isSequence && e.Any && string.IsNullOrEmpty(e.Name)) continue; if (!firstElement || (!isSequence && count > 0)) { ilg.InitElseIf(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 98ec06f03479a..596af9c47037d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -433,7 +433,7 @@ protected void WriteTypedPrimitive(string? name, string? ns, object o, bool xsiT private string GetQualifiedName(string name, string? ns) { - if (ns == null || ns.Length == 0) return name; + if (string.IsNullOrEmpty(ns)) return name; string? prefix = _w.LookupPrefix(ns); if (prefix == null) { @@ -518,7 +518,7 @@ protected void WriteStartElement(string name, string? ns, object? o, bool writeP if (writePrefixed && prefix == null && ns != null && ns.Length > 0) { prefix = _w.LookupPrefix(ns); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { prefix = NextPrefix(); } @@ -527,7 +527,7 @@ protected void WriteStartElement(string name, string? ns, object? o, bool writeP { xmlns.TryLookupPrefix(ns, out prefix); } - if (needEmptyDefaultNamespace && prefix == null && ns != null && ns.Length != 0) + if (needEmptyDefaultNamespace && prefix == null && !string.IsNullOrEmpty(ns)) prefix = NextPrefix(); _w.WriteStartElement(prefix, name, ns); if (_namespaces != null) @@ -536,9 +536,9 @@ protected void WriteStartElement(string name, string? ns, object? o, bool writeP { string alias = qname.Name; string? aliasNs = qname.Namespace; - if (alias.Length == 0 && (aliasNs == null || aliasNs.Length == 0)) + if (alias.Length == 0 && string.IsNullOrEmpty(aliasNs)) continue; - if (aliasNs == null || aliasNs.Length == 0) + if (string.IsNullOrEmpty(aliasNs)) { if (alias.Length > 0) throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlns, alias)); @@ -606,7 +606,7 @@ protected void WriteNullTagEncoded(string? name) protected void WriteNullTagEncoded(string? name, string? ns) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) return; WriteStartElement(name, ns, null, true); _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); @@ -620,7 +620,7 @@ protected void WriteNullTagLiteral(string? name) protected void WriteNullTagLiteral(string? name, string? ns) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) return; WriteStartElement(name, ns, null, false); _w.WriteAttributeString("nil", XmlSchema.InstanceNamespace, "true"); @@ -634,7 +634,7 @@ protected void WriteEmptyTag(string? name) protected void WriteEmptyTag(string? name, string? ns) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) return; WriteStartElement(name, ns, null, false); _w.WriteEndElement(); @@ -958,7 +958,7 @@ protected void WriteAttribute(string localName, string? ns, string? value) { string? prefix = _w.LookupPrefix(ns); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { prefix = "xml"; } @@ -1157,7 +1157,7 @@ protected void WriteElementQualifiedName(string localName, string? ns, XmlQualif protected void WriteElementQualifiedName(string localName, string? ns, XmlQualifiedName? value, XmlQualifiedName? xsiType) { if (value == null) return; - if (value.Namespace == null || value.Namespace.Length == 0) + if (string.IsNullOrEmpty(value.Namespace)) { WriteStartElement(localName, ns, null, true); WriteAttribute("xmlns", ""); @@ -1446,7 +1446,7 @@ protected void WriteNamespaceDeclarations(XmlSerializerNamespaces? xmlns) throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns)); } } - string? oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); + string? oldPrefix = string.IsNullOrEmpty(ns) ? null : Writer.LookupPrefix(ns); if (oldPrefix == null || oldPrefix != prefix) { @@ -2028,7 +2028,7 @@ internal static string GetStringForCreateInstance(string type, string? cast, boo createInstance.Append(".NonPublic"); } - if (arg == null || arg.Length == 0) + if (string.IsNullOrEmpty(arg)) { createInstance.Append(", null, new object[0], null)"); } @@ -2466,7 +2466,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) { - if (values[i] == null || values[i].Length == 0) + if (string.IsNullOrEmpty(values[i])) continue; if (i > 0) Writer.WriteLine(" | "); @@ -4476,7 +4476,7 @@ private static string FindChoiceEnumValue(ElementAccessor element, EnumMapping c } } } - if (enumValue == null || enumValue.Length == 0) + if (string.IsNullOrEmpty(enumValue)) { if (element.Any && element.Name.Length == 0) { 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 5a6e1169a697d..86048ea3287bd 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 @@ -215,7 +215,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) { - if (values[i] == null || values[i].Length == 0) + if (string.IsNullOrEmpty(values[i])) continue; if (i > 0) enumDefaultValue += ", "; @@ -2296,7 +2296,7 @@ private static string FindChoiceEnumValue(ElementAccessor element, EnumMapping c } } } - if (enumValue == null || enumValue.Length == 0) + if (string.IsNullOrEmpty(enumValue)) { if (element.Any && element.Name.Length == 0) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index 07b6bb93691a7..931ac4de8459d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -311,12 +311,7 @@ internal static string ToBinHexString(byte[] inArray) /// public static string VerifyName(string name) { - ArgumentNullException.ThrowIfNull(name); - - if (name.Length == 0) - { - throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name); // parse name int endPos = ValidateNames.ParseNameNoNamespaces(name, 0); @@ -374,12 +369,7 @@ public static string VerifyNCName(string name) internal static string VerifyNCName(string name, ExceptionType exceptionType) { - ArgumentNullException.ThrowIfNull(name); - - if (name.Length == 0) - { - throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); - } + ArgumentException.ThrowIfNullOrEmpty(name); int end = ValidateNames.ParseNCName(name, 0); @@ -474,7 +464,7 @@ internal static string VerifyNMTOKEN(string name, ExceptionType exceptionType) internal static Exception? TryVerifyNMTOKEN(string name) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) { return new XmlException(SR.Xml_EmptyName, string.Empty); } @@ -1403,7 +1393,7 @@ internal static void VerifyCharData(string? data, ExceptionType exceptionType) internal static void VerifyCharData(string? data, ExceptionType invCharExceptionType, ExceptionType invSurrogateExceptionType) { - if (data == null || data.Length == 0) + if (string.IsNullOrEmpty(data)) { return; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs index 55f27101c9aa3..8fca67140cbca 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs @@ -114,7 +114,7 @@ public override bool Equals([NotNullWhen(true)] object? other) /// public static string ToString(string name, string? ns) { - return ns == null || ns.Length == 0 ? name : $"{ns}:{name}"; + return string.IsNullOrEmpty(ns) ? name : $"{ns}:{name}"; } // --------- Some useful internal stuff ----------------- diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs index b5df8713be87c..384b8dc56d619 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs @@ -52,7 +52,7 @@ public virtual Uri ResolveUri(Uri? baseUri, string? relativeUri) } else { - if (relativeUri == null || relativeUri.Length == 0) + if (string.IsNullOrEmpty(relativeUri)) { return baseUri; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs index 531a7ce538cd1..88071e1c692c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs @@ -160,7 +160,7 @@ public MethodInfo DefineMethod(string name, Type returnType, Type[] paramTypes, for (int i = 0; i < paramNames.Length; i++) { - if (paramNames[i] != null && paramNames[i]!.Length != 0) + if (!string.IsNullOrEmpty(paramNames[i])) methBldr.DefineParameter(i + (isRaw ? 1 : 2), ParameterAttributes.None, paramNames[i]); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs index 3112752bd5266..574901728e1eb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs @@ -114,8 +114,8 @@ private void WriteAnnotations(object? ann) return; } - if (s != null && s.Length != 0) - this.writer.WriteComment(name != null && name.Length != 0 ? $"{name}: {s}" : s); + if (!string.IsNullOrEmpty(s)) + this.writer.WriteComment(!string.IsNullOrEmpty(name) ? $"{name}: {s}" : s); } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs index 33b375440b3d4..e26f8377740ad 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs @@ -84,7 +84,7 @@ public override void WriteStartAttribute(string? prefix, string localName, strin { int hashCode; int idx = 0; - Debug.Assert(localName != null && localName.Length != 0 && prefix != null && ns != null); + Debug.Assert(!string.IsNullOrEmpty(localName) && prefix != null && ns != null); // Compute hashcode based on first letter of the localName hashCode = (1 << ((int)localName[0] & 31)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index b8eaf1f89c73b..3c62109ce0548 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -159,7 +159,7 @@ public override void WriteDocType(string name, string? pubid, string? sysid, str /// public override void WriteStartElement(string? prefix, string localName, string? ns) { - Debug.Assert(prefix != null && localName != null && localName.Length != 0 && ns != null, "Invalid argument"); + Debug.Assert(prefix != null && !string.IsNullOrEmpty(localName) && ns != null, "Invalid argument"); Debug.Assert(ValidateNames.ValidateName(prefix, localName, ns, XPathNodeType.Element, ValidateNames.Flags.All), "Name validation failed"); // Xml state transitions @@ -1396,7 +1396,7 @@ private string CheckAttributePrefix(string prefix, string ns) private string RemapPrefix(string prefix, string ns, bool isElemPrefix) { string? genPrefix; - Debug.Assert(prefix != null && ns != null && ns.Length != 0); + Debug.Assert(prefix != null && !string.IsNullOrEmpty(ns)); _conflictPrefixes ??= new Dictionary(16); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs index 36aa9e793e1cb..e55a41538f1c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs @@ -85,7 +85,7 @@ private static void AppendTrimmed(StringBuilder sb, string value, int startIndex internal string? MarkOutError() { - if (queryString == null || queryString.Trim(' ').Length == 0) + if (queryString == null || queryString.AsSpan().Trim(' ').IsEmpty) { return null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs index 91ddc06d99758..42f7802e23f9e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs @@ -2824,7 +2824,7 @@ private XmlQualifiedName ResolveQName(bool ignoreDefaultNs, string qname) // Does not suppress errors private void ParseWhitespaceRules(string elements, bool preserveSpace) { - if (elements != null && elements.Length != 0) + if (!string.IsNullOrEmpty(elements)) { string[] tokens = XmlConvert.SplitString(elements); for (int i = 0; i < tokens.Length; i++) @@ -2834,7 +2834,7 @@ private void ParseWhitespaceRules(string elements, bool preserveSpace) { namespaceName = _compiler.CreatePhantomNamespace(); } - else if (prefix == null || prefix.Length == 0) + else if (string.IsNullOrEmpty(prefix)) { namespaceName = prefix; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BuilderInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BuilderInfo.cs index 6b09baf8c7331..f426d6dc57ec6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BuilderInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/BuilderInfo.cs @@ -169,7 +169,7 @@ internal string Value internal void ValueAppend(string? s, bool disableEscaping) { - if (s == null || s.Length == 0) + if (string.IsNullOrEmpty(s)) { return; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs index 5e6efac9ff716..d77aef50b0eb5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs @@ -431,7 +431,7 @@ internal void AddDecimalFormat(XmlQualifiedName name, DecimalFormat formatinfo) // the value is ignored iff forwards-compatible mode is on. private string[]? ResolvePrefixes(string tokens) { - if (tokens == null || tokens.Length == 0) + if (string.IsNullOrEmpty(tokens)) { return null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScopeManager.cs index ebeaaa30b3ab8..d67eaf1db0a0c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/InputScopeManager.cs @@ -77,7 +77,7 @@ internal void PushNamespace(string prefix, string nspace) Debug.Assert(nspace != null); _scopeStack.AddNamespace(prefix, nspace, _defaultNS); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { _defaultNS = nspace; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs index a9a3748305a8a..be20a0549ac27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs @@ -681,7 +681,7 @@ Parse format string into format tokens (alphanumeric) and separators [return: NotNullIfNotNull(nameof(formatString))] private static List? ParseFormat(string? formatString) { - if (formatString == null || formatString.Length == 0) + if (string.IsNullOrEmpty(formatString)) { return null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs index 42b57d2a76f76..6be5ce1ee5a7c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutputScopeManager.cs @@ -69,7 +69,7 @@ internal void PushNamespace(string prefix, string nspace) Debug.Assert(nspace != null); CurrentElementScope.AddNamespace(prefix, nspace, _defaultNS); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { _defaultNS = nspace; } @@ -115,7 +115,7 @@ internal void PopScope() Debug.Assert(prefix != null); thisScope = true; - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { return _defaultNS; } diff --git a/src/libraries/System.Private.Xml/tests/Writers/RwFactory/CXmlDriverEngine.cs b/src/libraries/System.Private.Xml/tests/Writers/RwFactory/CXmlDriverEngine.cs index a90e503014dc1..7d38b1255f535 100644 --- a/src/libraries/System.Private.Xml/tests/Writers/RwFactory/CXmlDriverEngine.cs +++ b/src/libraries/System.Private.Xml/tests/Writers/RwFactory/CXmlDriverEngine.cs @@ -667,7 +667,7 @@ private void ParseControlFile(string testCaseNamePrefix, string controlFile, str // no 'implemented' variations satisfying the filter testCase = new CXmlDriverEmptyTestCase(testCaseName, testCaseDescription, " no variations with @Implemented='True' " + - (_requiredLanguage != null && _requiredLanguage.Length != 0 ? " and @Language='" + _requiredLanguage + "'" : "") + + (!string.IsNullOrEmpty(_requiredLanguage) ? " and @Language='" + _requiredLanguage + "'" : "") + (filterXPath == null ? "" : " and satisfying '" + filterXPath + "'"), _testModule); // add test case diff --git a/src/libraries/System.Private.Xml/tests/XmlConvert/VerifyNameTests3.cs b/src/libraries/System.Private.Xml/tests/XmlConvert/VerifyNameTests3.cs index ce3f00f008d59..1655766bdd613 100644 --- a/src/libraries/System.Private.Xml/tests/XmlConvert/VerifyNameTests3.cs +++ b/src/libraries/System.Private.Xml/tests/XmlConvert/VerifyNameTests3.cs @@ -42,8 +42,8 @@ public override void AddChildren() AddChild(new CVariation(v17) { Attribute = new Variation("Test for VerifyNMTOKEN(null)") { Param = 1 } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyPublicId(String.Empty)") { Params = new object[] { 6, null } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyWhitespace(String.Empty)") { Params = new object[] { 7, null } } }); - AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyName(String.Empty)") { Params = new object[] { 2, typeof(ArgumentNullException) } } }); - AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNCName(String.Empty)") { Params = new object[] { 3, typeof(ArgumentNullException) } } }); + AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyName(String.Empty)") { Params = new object[] { 2, typeof(ArgumentException) } } }); + AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNCName(String.Empty)") { Params = new object[] { 3, typeof(ArgumentException) } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyXmlChars(String.Empty)") { Params = new object[] { 5, null } } }); AddChild(new CVariation(v18) { Attribute = new Variation("Test for VerifyNMTOKEN(String.Empty)") { Params = new object[] { 1, typeof(XmlException) } } }); } diff --git a/src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaValidatorApi/ValidateMisc.cs b/src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaValidatorApi/ValidateMisc.cs index 8a557359b428f..baaa85e2489c7 100644 --- a/src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaValidatorApi/ValidateMisc.cs +++ b/src/libraries/System.Private.Xml/tests/XmlSchema/XmlSchemaValidatorApi/ValidateMisc.cs @@ -941,8 +941,7 @@ public void XSDValidationGeneratesInvalidError_2() private string EnsureTrailingSlash(string path) { - if (string.IsNullOrEmpty(path)) - throw new ArgumentException(); + ArgumentException.ThrowIfNullOrEmpty(path); return path[path.Length - 1] == Path.DirectorySeparatorChar ? path : diff --git a/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XsltArgumentList.cs b/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XsltArgumentList.cs index 6bf0e435b2e60..4083c522d31ea 100644 --- a/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XsltArgumentList.cs +++ b/src/libraries/System.Private.Xml/tests/Xslt/XslCompiledTransformApi/XsltArgumentList.cs @@ -1051,11 +1051,11 @@ public void AddParam3() { m_xsltArg.AddParam(szEmpty, szEmpty, "Test1"); } - catch (System.ArgumentNullException) + catch (System.ArgumentException) { return; } - _output.WriteLine("System.ArgumentNullException not thrown for param name empty string"); + _output.WriteLine("System.ArgumentException not thrown for param name empty string"); Assert.True(false); } diff --git a/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/CXslTArgumentList.cs b/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/CXslTArgumentList.cs index dbd6ef93c6ca9..a2d2d0b00b4a3 100644 --- a/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/CXslTArgumentList.cs +++ b/src/libraries/System.Private.Xml/tests/Xslt/XslTransformApi/CXslTArgumentList.cs @@ -666,11 +666,11 @@ public void AddParam3() { m_xsltArg.AddParam(szEmpty, szEmpty, "Test1"); } - catch (System.ArgumentNullException) + catch (System.ArgumentException) { return; } - _output.WriteLine("System.ArgumentNullException not thrown for param name empty string"); + _output.WriteLine("System.ArgumentException not thrown for param name empty string"); Assert.True(false); } diff --git a/src/libraries/System.Reflection.Emit/src/Resources/Strings.resx b/src/libraries/System.Reflection.Emit/src/Resources/Strings.resx index 02f0c2865c2e8..ad9a578e61060 100644 --- a/src/libraries/System.Reflection.Emit/src/Resources/Strings.resx +++ b/src/libraries/System.Reflection.Emit/src/Resources/Strings.resx @@ -129,9 +129,6 @@ Assembly needs at least one module defined. - - AssemblyName.Name cannot be null or an empty string. - You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime. @@ -171,4 +168,4 @@ SizeConst parameter must be specified for UnmanagedType.ByValTStr type. - \ No newline at end of file + diff --git a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/AssemblyBuilderImpl.cs b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/AssemblyBuilderImpl.cs index 238be3976a40d..35c590a5efb20 100644 --- a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/AssemblyBuilderImpl.cs +++ b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/AssemblyBuilderImpl.cs @@ -25,10 +25,7 @@ internal AssemblyBuilderImpl(AssemblyName name, Assembly coreAssembly, IEnumerab name = (AssemblyName)name.Clone(); - if (string.IsNullOrEmpty(name.Name)) - { - throw new ArgumentException(SR.Argument_NullOrEmptyAssemblyName); - } + ArgumentException.ThrowIfNullOrEmpty(name.Name, "AssemblyName.Name"); _assemblyName = name; _coreAssembly = coreAssembly; diff --git a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/PseudoCustomAttributesData.cs b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/PseudoCustomAttributesData.cs index 93dd864ccedf1..d2c95732cfee8 100644 --- a/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/PseudoCustomAttributesData.cs +++ b/src/libraries/System.Reflection.Emit/src/System/Reflection/Emit/PseudoCustomAttributesData.cs @@ -29,7 +29,7 @@ internal DllImportData(string moduleName, string? entryPoint, MethodImportAttrib internal static DllImportData CreateDllImportData(CustomAttributeInfo attr, out bool preserveSig) { string? moduleName = (string?)attr._ctorArgs[0]; - if (moduleName == null || moduleName.Length == 0) + if (string.IsNullOrEmpty(moduleName)) { throw new ArgumentException(SR.Argument_DllNameCannotBeEmpty); } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.Modules.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.Modules.cs index c7cb4bd3143d8..f9f2d6a3c9bdd 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.Modules.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Assemblies/Ecma/EcmaAssembly.Modules.cs @@ -39,7 +39,7 @@ protected sealed override RoModule LoadModule(string moduleName, bool containsMe { Assembly containingAssembly = this; string location = containingAssembly.Location; - if (location == null || location.Length == 0) + if (string.IsNullOrEmpty(location)) return null; string? directoryPath = Path.GetDirectoryName(location); string modulePath = Path.Combine(directoryPath!, moduleName); diff --git a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/CodeExporter.cs b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/CodeExporter.cs index 266b0b0e2f172..32904a5881e31 100644 --- a/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/CodeExporter.cs +++ b/src/libraries/System.Runtime.Serialization.Schema/src/System/Runtime/Serialization/Schema/CodeExporter.cs @@ -1510,7 +1510,7 @@ private static void AddImportStatement(string? clrNamespace, CodeNamespace? code private static string GetClrNamespace(string? dataContractNamespace) { - if (dataContractNamespace == null || dataContractNamespace.Length == 0) + if (string.IsNullOrEmpty(dataContractNamespace)) return string.Empty; StringBuilder builder = new StringBuilder(); diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalEncoder.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalEncoder.cs index bdce0cf8f29aa..c2a267139c898 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalEncoder.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalEncoder.cs @@ -139,7 +139,7 @@ public void Encode(char[] buffer, int offset, int count) public void EncodeAttribute(string prefix, string localName, string value) { Encode(' '); - if (prefix == null || prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { Encode(localName); } diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalWriter.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalWriter.cs index 36d4c29778c59..a2ca0fa0c9e1f 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalWriter.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/Canonicalization/CryptoCanonicalization/CanonicalWriter.cs @@ -656,7 +656,7 @@ public override void WriteProcessingInstruction(string name, string text) public override void WriteQualifiedName(string localName, string ns) { - if (localName == null || localName.Length == 0) + if (string.IsNullOrEmpty(localName)) { throw new ArgumentNullException(nameof(localName)); } @@ -883,7 +883,7 @@ private void WriteStartElementCore(ref string prefix, string localName, string n ThrowBadStateException("WriteStartElement"); } - if (localName == null || localName.Length == 0) + if (string.IsNullOrEmpty(localName)) { throw new ArgumentNullException(nameof(localName)); } diff --git a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/DataContract.cs b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/DataContract.cs index 57825bdcc0188..91e57848757f7 100644 --- a/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/DataContract.cs +++ b/src/libraries/System.Runtime.Serialization.Xml/tests/SerializationTestTypes/DataContract.cs @@ -1393,7 +1393,7 @@ void ImportDataMembers() throw new Exception("TooManyDataMembers :" + field.DeclaringType.FullName + " :: " + field.Name); DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0]; DataMember memberContract = new DataMember(field); - if (memberAttribute.Name == null || memberAttribute.Name.Length == 0) + if (string.IsNullOrEmpty(memberAttribute.Name)) memberContract.Name = field.Name; else memberContract.Name = memberAttribute.Name; diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs index 50e13fde40d10..3fd260dd78786 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/SignedXml.cs @@ -825,7 +825,7 @@ private int GetReferenceLevel(int index, ArrayList references) if (_refProcessed[index]) return _refLevelCache[index]; _refProcessed[index] = true; Reference reference = (Reference)references[index]!; - if (reference.Uri == null || reference.Uri.Length == 0 || (reference.Uri.Length > 0 && reference.Uri[0] != '#')) + if (string.IsNullOrEmpty(reference.Uri) || (reference.Uri.Length > 0 && reference.Uri[0] != '#')) { _refLevelCache[index] = 0; return 0; 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 cadad48a17fa4..0483550c4b781 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 @@ -621,9 +621,9 @@ internal static int GetHexArraySize(byte[] hex) // Mimic the behavior of the X509IssuerSerial constructor with null and empty checks internal static X509IssuerSerial CreateX509IssuerSerial(string? issuerName, string? serialNumber) { - if (issuerName == null || issuerName.Length == 0) + if (string.IsNullOrEmpty(issuerName)) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(issuerName)); - if (serialNumber == null || serialNumber.Length == 0) + if (string.IsNullOrEmpty(serialNumber)) throw new ArgumentException(SR.Arg_EmptyOrNullString, nameof(serialNumber)); return new X509IssuerSerial() diff --git a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs index ff57f6e717030..9633e0111c71a 100644 --- a/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs +++ b/src/libraries/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/XmlDecryptionTransform.cs @@ -100,7 +100,7 @@ public override void LoadInnerXml(XmlNodeList nodeList) { // the Uri is required string? uri = Utils.GetAttribute(elem, "URI", Consts.XmlDecryptionTransformNamespaceUrl); - if (uri == null || uri.Length == 0 || uri[0] != '#') + if (string.IsNullOrEmpty(uri) || uri[0] != '#') throw new CryptographicException(SR.Cryptography_Xml_UriRequired); if (!Utils.VerifyAttributes(elem, "URI")) { diff --git a/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx b/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx index f31af3b55e7b5..0172bc6e6f4ea 100644 --- a/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Cryptography/src/Resources/Strings.resx @@ -66,9 +66,6 @@ String cannot be empty or null. - - The '{0}' string cannot be empty or null. - Span may not be empty. @@ -183,9 +180,6 @@ Accessing a hash algorithm by manipulating the HashName property is not supported on this platform. Instead, you must instantiate one of the supplied subtypes (such as HMACSHA1.) - - CryptoConfig cannot add a mapping for a null or empty name. - The KDF for algorithm '{0}' requires a char-based password input. diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs index d7397d28223b9..0ad4b84fa8043 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/CryptoConfig.cs @@ -317,10 +317,7 @@ public static void AddAlgorithm(Type algorithm, params string[] names) // throw an exception if we find an invalid name partway through the list. foreach (string name in algorithmNames) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name, nameof(names)); } // Everything looks valid, so we're safe to add the name mappings. @@ -512,10 +509,7 @@ public static void AddOID(string oid, params string[] names) // exception if an invalid name is found further down the array. foreach (string name in oidNames) { - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException(SR.Cryptography_AddNullOrEmptyName); - } + ArgumentException.ThrowIfNullOrEmpty(name, nameof(names)); } // Everything is valid, so we're good to lock the hash table and add the application mappings diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs index af3605ec0da7f..3a6c498571110 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X500DistinguishedNameBuilder.cs @@ -97,9 +97,7 @@ public void Add(Oid oid, string value, UniversalTagNumber? stringEncodingType = { ArgumentNullException.ThrowIfNull(oid); ArgumentNullException.ThrowIfNull(value); - - if (string.IsNullOrEmpty(oid.Value)) - throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid)); + ArgumentException.ThrowIfNullOrEmpty(oid.Value); UniversalTagNumber tag = GetAndValidateTagNumber(stringEncodingType); EncodeComponent(oid.Value, value, tag); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509AuthorityInformationAccessExtension.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509AuthorityInformationAccessExtension.cs index c5e026207a3ce..7607900a31875 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509AuthorityInformationAccessExtension.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509AuthorityInformationAccessExtension.cs @@ -169,13 +169,7 @@ public IEnumerable EnumerateUris(string accessMethodOid) public IEnumerable EnumerateUris(Oid accessMethodOid) { ArgumentNullException.ThrowIfNull(accessMethodOid); - - if (string.IsNullOrEmpty(accessMethodOid.Value)) - { - throw new ArgumentException( - SR.Format(SR.Arg_EmptyOrNullString_Named, "accessMethodOid.Value"), - nameof(accessMethodOid)); - } + ArgumentException.ThrowIfNullOrEmpty(accessMethodOid.Value); return EnumerateUris(accessMethodOid.Value); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs index a34104e7f14d7..72739223b3391 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Extension.cs @@ -38,10 +38,7 @@ public X509Extension(Oid oid, byte[] rawData, bool critical) public X509Extension(Oid oid, ReadOnlySpan rawData, bool critical) : base(oid, rawData) { - if (base.Oid?.Value == null) - throw new ArgumentNullException(nameof(oid)); - if (base.Oid.Value.Length == 0) - throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid)); + ArgumentException.ThrowIfNullOrEmpty(base.Oid?.Value, "oid.Value"); Critical = critical; } @@ -71,11 +68,7 @@ public X509Extension(string oid, ReadOnlySpan rawData, bool critical) internal X509Extension(Oid oid, byte[] rawData, bool critical, bool skipCopy) : base(oid, rawData, skipCopy) { - if (base.Oid?.Value == null) - throw new ArgumentNullException(nameof(oid)); - - if (base.Oid.Value.Length == 0) - throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid)); + ArgumentException.ThrowIfNullOrEmpty(base.Oid?.Value, "oid.Value"); Critical = critical; } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.Android.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.Android.cs index c1bb2793803a4..aeaceea640718 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.Android.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.Android.cs @@ -89,7 +89,7 @@ public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool public X509ContentType GetCertContentType(ReadOnlySpan rawData) { - if (rawData == null || rawData.Length == 0) + if (rawData.IsEmpty) throw new CryptographicException(); X509ContentType contentType = Interop.AndroidCrypto.X509GetContentType(rawData); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.iOS.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.iOS.cs index f9ff5f38b87af..76ac0eaec4209 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.iOS.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.iOS.cs @@ -49,7 +49,7 @@ public X509ContentType GetCertContentType(ReadOnlySpan rawData) { const int errSecUnknownFormat = -25257; - if (rawData == null || rawData.Length == 0) + if (rawData.IsEmpty) { // Throw to match Windows and Unix behavior. throw Interop.AppleCrypto.CreateExceptionForOSStatus(errSecUnknownFormat); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.macOS.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.macOS.cs index 2e07e6803b44b..7a6e555b12ced 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.macOS.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Pal.macOS.cs @@ -111,7 +111,7 @@ private static DSA DecodeDsaPublicKey(byte[] encodedKeyValue, byte[] encodedPara public X509ContentType GetCertContentType(ReadOnlySpan rawData) { const int errSecUnknownFormat = -25257; - if (rawData == null || rawData.Length == 0) + if (rawData.IsEmpty) { // Throw to match Windows and Unix behavior. throw Interop.AppleCrypto.CreateExceptionForOSStatus(errSecUnknownFormat); diff --git a/src/libraries/System.Security.Cryptography/tests/CryptoConfigTests.cs b/src/libraries/System.Security.Cryptography/tests/CryptoConfigTests.cs index 964b4668a61a9..b9e99144f6b8f 100644 --- a/src/libraries/System.Security.Cryptography/tests/CryptoConfigTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/CryptoConfigTests.cs @@ -209,7 +209,7 @@ public static void AddOID_MapNameToOID_ReturnsMapped() [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public static void AddOID_EmptyString_Throws() { - AssertExtensions.Throws(null, () => CryptoConfig.AddOID(string.Empty, string.Empty)); + AssertExtensions.Throws("names", () => CryptoConfig.AddOID(string.Empty, string.Empty)); } [Fact] @@ -257,7 +257,7 @@ private class AESFancy [SkipOnPlatform(TestPlatforms.Browser, "Not supported on Browser")] public static void AddAlgorithm_EmptyString_Throws() { - AssertExtensions.Throws(null, () => CryptoConfig.AddAlgorithm(typeof(CryptoConfigTests), string.Empty)); + AssertExtensions.Throws("names", () => CryptoConfig.AddAlgorithm(typeof(CryptoConfigTests), string.Empty)); } [Fact] diff --git a/src/libraries/System.Security.Cryptography/tests/X509Certificates/ExtensionsTests/AuthorityInformationAccessTests.cs b/src/libraries/System.Security.Cryptography/tests/X509Certificates/ExtensionsTests/AuthorityInformationAccessTests.cs index 42b0f9e1ab25b..cfa679403a092 100644 --- a/src/libraries/System.Security.Cryptography/tests/X509Certificates/ExtensionsTests/AuthorityInformationAccessTests.cs +++ b/src/libraries/System.Security.Cryptography/tests/X509Certificates/ExtensionsTests/AuthorityInformationAccessTests.cs @@ -272,8 +272,8 @@ public static void EnumerateNull() Assert.Throws("accessMethodOid", () => aia.EnumerateUris((string)null)); Assert.Throws("accessMethodOid", () => aia.EnumerateUris((Oid)null)); - Assert.Throws("accessMethodOid", () => aia.EnumerateUris(new Oid(null, "potato"))); - Assert.Throws("accessMethodOid", () => aia.EnumerateUris(new Oid("", "potato"))); + Assert.Throws("accessMethodOid.Value", () => aia.EnumerateUris(new Oid(null, "potato"))); + Assert.Throws("accessMethodOid.Value", () => aia.EnumerateUris(new Oid("", "potato"))); } } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/NTAccount.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/NTAccount.cs index b4ccc24f9ee32..539a2bf4924fa 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/NTAccount.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/NTAccount.cs @@ -45,7 +45,7 @@ public NTAccount(string domainName, string accountName) throw new ArgumentException(SR.IdentityReference_DomainNameTooLong, nameof(domainName)); } - if (domainName == null || domainName.Length == 0) + if (string.IsNullOrEmpty(domainName)) { _name = accountName; } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs index 613d551855e25..f875934f24e75 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs @@ -49,7 +49,7 @@ public WindowsPrincipal(WindowsIdentity ntIdentity) public override bool IsInRole(string role) { - if (role == null || role.Length == 0) + if (string.IsNullOrEmpty(role)) return false; NTAccount ntAccount = new NTAccount(role); diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs index 9f240dead871b..0c1a487b26f73 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceController.cs @@ -65,8 +65,14 @@ public ServiceController(string name, string machineName) if (!CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.BadMachineName, machineName)); - if (string.IsNullOrEmpty(name)) - throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(name), name)); + if (name is null) + { + throw new ArgumentNullException(nameof(name)); + } + if (name.Length == 0) + { + throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(name), name), nameof(name)); + } _machineName = machineName; _eitherName = name; diff --git a/src/libraries/System.ServiceProcess.ServiceController/tests/SafeServiceControllerTests.cs b/src/libraries/System.ServiceProcess.ServiceController/tests/SafeServiceControllerTests.cs index 8fe4407e2fd65..0e4210f0a0b45 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/tests/SafeServiceControllerTests.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/tests/SafeServiceControllerTests.cs @@ -59,12 +59,11 @@ public static void GetServices() Assert.True(foundOtherSvc, "foundOtherSvc"); } - [Theory] - [InlineData(null)] - [InlineData("")] - public static void ConstructWithBadServiceName(string value) + [Fact] + public static void ConstructWithBadServiceName() { - Assert.Throws(() => new ServiceController(value)); + Assert.ThrowsAny(() => new ServiceController(null)); + Assert.Throws(() => new ServiceController("")); } [Fact] diff --git a/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs b/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs index 6fe2156834919..659cae79744ec 100644 --- a/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs +++ b/src/libraries/System.Speech/src/Result/RecognizedWordUnit.cs @@ -25,7 +25,7 @@ public RecognizedWordUnit(string text, float confidence, string pronunciation, s throw new ArgumentOutOfRangeException(SR.Get(SRID.InvalidConfidence)); } - _text = text == null || text.Length == 0 ? null : text; + _text = string.IsNullOrEmpty(text) ? null : text; _confidence = confidence; _pronunciation = pronunciation == null || pronunciation.Length == 0 ? null : pronunciation; _lexicalForm = lexicalForm; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index 70c6cf24ee811..8fed4d70cb8f9 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -227,7 +227,7 @@ public static Enlistment Reenlist( private static OletxTransactionManager CheckTransactionManager(string? nodeName) { OletxTransactionManager tm = DistributedTransactionManager; - if (!((tm.NodeName == null && (nodeName == null || nodeName.Length == 0)) || + if (!((tm.NodeName == null && string.IsNullOrEmpty(nodeName)) || (tm.NodeName != null && tm.NodeName.Equals(nodeName)))) { throw new ArgumentException(SR.InvalidRecoveryInformation, "recoveryInformation");